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

if (variable.constructor == 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 (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}

当我发布这个问题时,我使用的JQuery版本没有包含isArray函数。如果是这样的话,我可能会使用它,相信该实现是执行这种特定类型检查的最佳浏览器独立方式。

因为JQuery现在确实提供了这个功能,所以我会一直使用它。。。

$.isArray(obj);

(自1.6.2版起)它仍然使用以下形式的字符串比较来实现

toString.call(obj) === "[object Array]"

对于那些编码高尔夫的人来说,这是一个字符最少的不可靠测试:

function isArray(a) {
  return a.map;
}

这通常在遍历/展平层次结构时使用:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

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

例如。,

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

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