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

if (variable.constructor == Array)

当前回答

我认为使用myObj.constructor==Object和myArray.constructor==Array是最好的方法。它几乎比使用toString()快20倍。如果您使用自己的构造函数扩展对象,并希望这些创建也被视为“对象”,那么这是行不通的,但否则它会更快。typeof与构造函数方法一样快,但typeof[]=='object'返回true,这通常是不可取的。http://jsperf.com/constructor-vs-tostring

需要注意的一点是null.constructor将抛出一个错误,因此如果您可能要检查null值,则必须首先执行以下操作:(testThing!==null){}

其他回答

我想我会为那些可能已经在脚本中使用Undercore.js库的人添加另一个选项。Undercore.js有一个isArray()函数(请参见http://underscorejs.org/#isArray).

_.isArray(object) 

如果对象是数组,则返回true。

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

我注意到有人提到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]'; 
}

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