如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
当前回答
代码引用自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);};
其他回答
在现代浏览器(以及一些传统浏览器)中,您可以
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)
您还可以使用:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
在我看来,这是一个非常优雅的解决方案,但对每个人来说都是自己的。
编辑:
截至ES5,现在还有:
Array.isArray(value);
但这将在旧浏览器上打破,除非您使用的是polyfills(基本上…IE8或类似)。
我注意到有人提到jQuery,但我不知道有isArray()函数。原来它是在1.3版中添加的。
jQuery按照Peter的建议实现它:
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
我已经对jQuery很有信心(尤其是他们的跨浏览器兼容性技术),我要么升级到1.3版并使用他们的功能(前提是升级不会导致太多问题),要么直接在代码中使用建议的方法。
非常感谢您的建议。
我喜欢Brian的回答:
function is_array(o){
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]') {
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
} else{
// may want to change return value to something more desirable
return -1;
}
}
但你可以这样做:
return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
来自w3schools:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}