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

if (variable.constructor == Array)

当前回答

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

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

其他回答

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

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

Array.prototype.isArray = true;

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

var box = doSomething();

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

isArray仅在其为数组时可用

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

jQuery按照Peter的建议实现它:

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

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

非常感谢您的建议。

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

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

我喜欢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(项目长度)//这是一个数组其他的//不是数组