确定对象是否是数组的最佳方法是什么

2024-03-14

据我所知,有三种方法可以判断一个对象是否是数组

by isArray功能(如果已实现)

Array.isArray()

by toString

Object.prototype.toString.apply( obj ) === "[object Array]"

and by instanceof

obj instanceof Array

有什么理由选择其中之一而不是其他吗?


最好的方法可能是使用标准Array.isArray() https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray,如果它是由引擎实现的:

isArray = Array.isArray(myObject)

MDN https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility建议使用toString()方法当Array.isArray没有实现:

兼容性

在创建任何其他代码之前运行以下代码 Array.isArray(如果它本身不可用)。这依赖于 Object.prototype.toString 保持不变并调用解析为 原生 Function.prototype.call 方法。

if(!Array.isArray) {  
  Array.isArray = function (arg) {  
    return Object.prototype.toString.call(arg) == '[object Array]';  
  };  
}

Both jQuery and underscore.js[source] https://github.com/documentcloud/underscore/blob/39b07d7b2cdbcf2f37b1239772ba58617f7c3650/underscore.js#L654 take the toString() === "[object Array]" way.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

确定对象是否是数组的最佳方法是什么 的相关文章

随机推荐