如何在JavaScript中检查变量是否为数组?

if (variable.constructor == Array)

当前回答

我用的是这行代码:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}

其他回答

通过Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

Crockford提到的主要失败是无法正确确定在不同上下文(例如窗口)中创建的数组。如果这还不够的话,该页面有一个更复杂的版本。

您还可以使用:

if (value instanceof Array) {
  alert('value is Array!');
} else {
  alert('Not an array');
}

在我看来,这是一个非常优雅的解决方案,但对每个人来说都是自己的。

编辑:

截至ES5,现在还有:

Array.isArray(value);

但这将在旧浏览器上打破,除非您使用的是polyfills(基本上…IE8或类似)。

这是一个老问题,但有同样的问题,我找到了一个非常优雅的解决方案,我想分享。

将原型添加到Array使其非常简单

Array.prototype.isArray = true;

现在,如果您有一个要测试的对象,看看它是否是一个数组,您只需要检查新属性

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray仅在其为数组时可用

当我发布这个问题时,我使用的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)