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

if (variable.constructor == Array)

当前回答

如果您只处理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;
}

我喜欢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([]);

您还可以使用:

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

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

编辑:

截至ES5,现在还有:

Array.isArray(value);

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

我刚想到的:

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

通用解决方案如下:

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