如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
当前回答
在现代浏览器(以及一些传统浏览器)中,您可以
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)
其他回答
我想我会为那些可能已经在脚本中使用Undercore.js库的人添加另一个选项。Undercore.js有一个isArray()函数(请参见http://underscorejs.org/#isArray).
_.isArray(object)
如果对象是数组,则返回true。
我刚想到的:
if(项目长度)//这是一个数组其他的//不是数组
对于那些编码高尔夫的人来说,这是一个字符最少的不可靠测试:
function isArray(a) {
return a.map;
}
这通常在遍历/展平层次结构时使用:
function golf(a) {
return a.map?[].concat.apply([],a.map(golf)):a;
}
input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
通用解决方案如下:
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
来自w3schools:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}