如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
当前回答
这是一个老问题,但有同样的问题,我找到了一个非常优雅的解决方案,我想分享。
将原型添加到Array使其非常简单
Array.prototype.isArray = true;
现在,如果您有一个要测试的对象,看看它是否是一个数组,您只需要检查新属性
var box = doSomething();
if (box.isArray) {
// do something
}
isArray仅在其为数组时可用
其他回答
这是一个老问题,但有同样的问题,我找到了一个非常优雅的解决方案,我想分享。
将原型添加到Array使其非常简单
Array.prototype.isArray = true;
现在,如果您有一个要测试的对象,看看它是否是一个数组,您只需要检查新属性
var box = doSomething();
if (box.isArray) {
// do something
}
isArray仅在其为数组时可用
在现代浏览器(以及一些传统浏览器)中,您可以
Array.isArray(obj)
(支持Chrome 5、Firefox 4.0、IE 9、Opera 10.5和Safari 5)
如果需要支持旧版本的IE,可以使用es5垫片来polyfill Array.isArray;或添加以下内容
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
如果使用jQuery,可以使用jQuery.isArray(obj)或$.isArra(obj
如果不需要检测在不同帧中创建的数组,也可以只使用instanceof
obj instanceof Array
注意:可以用于访问函数参数的arguments关键字不是Array,尽管它(通常)的行为类似于:
var func=函数(){console.log(参数)//[1,2,3]console.log(arguments.length)//3console.log(Array.isArray(参数))//false!!!console.log(argument.slice)//未定义(Array.prototype方法不可用)console.log([3,4,5].slice)//函数slice(){[本机代码]}}函数(1,2,3)
我认为使用myObj.constructor==Object和myArray.constructor==Array是最好的方法。它几乎比使用toString()快20倍。如果您使用自己的构造函数扩展对象,并希望这些创建也被视为“对象”,那么这是行不通的,但否则它会更快。typeof与构造函数方法一样快,但typeof[]=='object'返回true,这通常是不可取的。http://jsperf.com/constructor-vs-tostring
需要注意的一点是null.constructor将抛出一个错误,因此如果您可能要检查null值,则必须首先执行以下操作:(testThing!==null){}
通用解决方案如下:
Object.prototype.toString.call(obj)=='[object Array]'
从ECMAScript 5开始,正式的解决方案是:
Array.isArray(arr)
此外,对于旧的JavaScript库,您可以找到以下解决方案,尽管它不够准确:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
解决方案来自http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript
代码引用自https://github.com/miksago/Evan.js/blob/master/src/evan.js
var isArray = Array.isArray || function(obj) {
return !!(obj && obj.concat && obj.unshift && !obj.callee);};