在JavaScript中,判断一个对象的类型,通常会使用typeof和instanceof操作符
例如,我们通常会有如下写法
var array = new Array("Marry","Jack","Jerry");
//使用typeof操作符
console.log(typeof(array)); //输出object,注意是小写开头的object
//使用instanceof操作符
console.log(array instanceof Array); //输出true
typeof的返回值是字符串,有六种:"number"、"string"、"function"、"boolean"、"object"、"undefined"
从以上的返回值中我们可以发现没有"array",说明typeof不能用于判断一个对象是否是Array类型,对Array类型对象的判断会返回一个值"object"
instanceof存在的问题是当Array对象在多个frame间传递时在IE中会出现问题,具体就不详细阐述了
上述方法都不能很好的解决判断一个对象是否为Array类型,在ECMA-262标准中有如下阐述:
Object.prototype.toString( ) When the toString method is called, the following steps are taken:
(1) Get the [[Class]] property of this object.
(2) Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
(3) Return Result (2)
根据上面的阐述,可写出如下的函数:
function isArray(obj) {
//call改变toString的this引用为待检测的对象,返回此对象的字符串表示
return Object.property.toString().call(obj) === '[object Array]';
}