如何在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)

其他回答

来自w3schools:

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

您还可以使用:

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

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

编辑:

截至ES5,现在还有:

Array.isArray(value);

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

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

有多种解决方案都有其独特之处。本页提供了一个很好的概述。一种可能的解决方案是:

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}

我注意到有人提到jQuery,但我不知道有isArray()函数。原来它是在1.3版中添加的。

jQuery按照Peter的建议实现它:

isArray: function( obj ) {
    return toString.call(obj) === "[object Array]";
},

我已经对jQuery很有信心(尤其是他们的跨浏览器兼容性技术),我要么升级到1.3版并使用他们的功能(前提是升级不会导致太多问题),要么直接在代码中使用建议的方法。

非常感谢您的建议。