如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
当前回答
我用的是这行代码:
if (variable.push) {
// variable is array, since AMAIK only arrays have push() method.
}
其他回答
在现代浏览器(以及一些传统浏览器)中,您可以
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)
代码引用自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);};
由于.length属性对于javascript中的数组是特殊的,因此可以简单地说
obj.length === +obj.length // true if obj is an array
Undercorejs和其他几个库使用这个简单的技巧。
我已经创建了一小段代码,它可以返回真正的类型。
我还不确定性能,但这是一种正确识别类型的尝试。
https://github.com/valtido/better-typeOf也在这里写了一些关于它的博客http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/
它的工作原理与当前类型的类似。
var user = [1,2,3]
typeOf(user); //[object Array]
它认为它可能需要一些微调,并且考虑到一些事情,我没有遇到或测试它。因此,无论是性能方面的改进,还是错误地重新移植类型of,都欢迎进一步的改进。
我喜欢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([]);