typeof
使用typeof来判断数据类型是最为常见的,但是typeof只能判断基本的数据类型,面对对象类型、null、Array返回的都是Object类型。
var str = '2323';
typeof str // string;
var num = 123;
typeof num // number;
var bn = false
typeof bn // boolean
typeof undefined // undefined
typeof null // object
typeof [1,2,3] // object
typeof {name: 3434} // object
typeof function(){} // function
注意:使用typeof判断function时,返回的是function。
Object.prototype.toString.call()
在javascript中,所有数据类型的父类都是Object,每一个继承Object的对象都有toString方法,因此在没有重写toString的情况下。toString方法返回的是[Object type],其中type是对象的类型,除了Object类型的对象外,其他类型直接使用 toString 方法时,会直接返回都是内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。
// 直接使用toString方法
var arr = [1, 2];
arr.toString(); // "1,2"
// 使用Object.prototype.toString.call()方法读取类型
Object.prototype.toString.call(arr); // '[object Array]'
使用Object.prototype.toString.call()判断数据类型的好处就是,所有基本的数据类型都能进行判断,包括null和undefined
Object.prototype.toString.call('string') // '[object String]'
Object.prototype.toString.call(123) // '[object Number]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined)// '[object undefined]'
Object.prototype.toString.call(function(){}) // '[object Function]'
Object.prototype.toString.call([1,2,3])// '[object Array]'
Object.prototype.toString.call({name: 'yf'}) // '[object Object]'
Object.prototype.toString.call(Symbol(1)) //'[object Symbol]'
// 注意Symbol是一种特殊的构造函数,创建实例时不需要使用new关键字
instanceof
判断数组类型我们还可以使用instanceof。 instanceof的具体判断流程如下:
function instanceof (A, B) {
var O = B.prototype;
var A = A.__proto__;
while(true) {
if (A === null) {
return false;
}else if(O === A) {
return true;
}
A = A.__proto__;
}
}
从上面的判断过程可以看出,instanceof 的内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。其实原型链的查找过程。A instanceof Array;这个判断的过程其实就是查找A的原型链中是否能找到B.prototype。
[] instanceof Array // true
[] instanceof Object // true
// [].__proto__ = Array.prototype
// Array.prototype.__proto__ = Object.prototype
// [].__proto__.__proto__ = Object.prototype;
为什么[] instanceof Object返回的也是true呢。因为在Javascript中一切皆对象,所有类型的最终原型都指向对象,这个概念我们可以查看原型链这一章的内容。
注意:instanceof 只能用来判断对象类型,原始类型不可以。
var str = '2233';
str instanceof String; // false;
var strObj = new String('2233');
strObj instanceof String // true
Array.isArray()
在ES5中新增了Array.isArray()方法,用来判断是否为数组。 当检测Array实例时,Array.isArray优于instanceof,当不存在Array.isArray()时,可以使用Object.prototype.toString.call()实现。
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
使用constructor方法
constructor属性返回对创建此对象的数组函数的引用。就是返回对象相应的构造函数。
[].constructor === Array // true;
var obj = new Object();
obj.constructor === Object // true;
"string".constructor === String // true