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

if (variable.constructor == Array)

当前回答

如果使用的是Angular,则可以使用Angular.isArray()函数

var myArray = [];
angular.isArray(myArray); // returns true

var myObj = {};
angular.isArray(myObj); //returns false

http://docs.angularjs.org/api/ng/function/angular.isArray

其他回答

我刚想到的:

if(项目长度)//这是一个数组其他的//不是数组

如果您只处理EcmaScript 5及以上版本,那么可以使用内置的Array.isArray函数

例如。,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false

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