JavaScript判断一个对象是否为数组

在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]';
}

转载于:https://my.oschina.net/migoo/blog/640044

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值