如何在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);};
其他回答
当我发布这个问题时,我使用的JQuery版本没有包含isArray函数。如果是这样的话,我可能会使用它,相信该实现是执行这种特定类型检查的最佳浏览器独立方式。
因为JQuery现在确实提供了这个功能,所以我会一直使用它。。。
$.isArray(obj);
(自1.6.2版起)它仍然使用以下形式的字符串比较来实现
toString.call(obj) === "[object 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)
您还可以使用:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
在我看来,这是一个非常优雅的解决方案,但对每个人来说都是自己的。
编辑:
截至ES5,现在还有:
Array.isArray(value);
但这将在旧浏览器上打破,除非您使用的是polyfills(基本上…IE8或类似)。
通用解决方案如下:
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
我喜欢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([]);