JavaScript 中 typeof 和 instanceof 常用来判断一个变量是否为空,或者是什么类型的。但它们之间还是有区别的:
typeOf:
typeOf操作符是确定一个变量是字符串,数值,布尔值还是undefine或者是object的最佳工具。
var s=’tom’,str=‘22’;
var b = true,
var i = 22;
var u ;
var n = null;
var o = new Object();
var fun = function(){}
typeof s;//’string'
typeof str;//’string'
typeof b; //‘boolean'
typeof i;//’number'
typeof u;//'undefine'
typeof n;//'object'
typeof o;//‘object'
typeof fun;//‘function'
instanceof:
instanceof操作符是确定一个对象是什么类型的对象的工具。
alert(person instanceof Object);//变量person是Object 对象吗?
alert(colors instanceof Array);//变量colors是Array 对象吗?
alert(pattern instanceof RegExp);//变量pattern是RegExp 对象吗?
所有引用类型的值都是Object的实例。
区别:typeof是判断变量是什么基本类型的;
instanceof是判断对象到底是什么类型的;
在英语中,type of 是某类, instance of 是某个例子
希望对你有帮助~
type of 是某类, instance of 是某个例子