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

if (variable.constructor == Array)

当前回答

我个人喜欢彼得的建议:https://stackoverflow.com/a/767499/414784(对于ECMAScript 3。对于ECMAScript 5,请使用Array.isArray())

然而,帖子上的评论表明,如果toString()被更改,那么检查数组的方法将失败。如果您真的想具体一些,并确保toString()没有更改,并且objects类属性([objectArray]是数组对象的类属性)没有问题,那么我建议您这样做:

//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
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; 
    }
}

注意,在JavaScript《最终指南》第6版7.10中,它说Array.isArray()是使用ECMAScript 5中的Object.pr原型.toString.call()实现的。还要注意,如果您要担心toString()的实现发生变化,那么您也应该担心其他内置方法也会发生变化。为什么使用push()?有人可以改变它!这种做法很愚蠢。上面的检查是为那些担心toString()更改的人提供的解决方案,但我认为检查是不必要的。

其他回答

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

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

$.isArray(obj);

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

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

我在这里尝试了大多数解决方案。但没有一个有效。然后我提出了一个简单的解决方案。希望它能帮助某人并节省他们的时间。

if(variable.constructor != undefined && variable.constructor.length > 0) {
        /// IT IS AN ARRAY
} else {
       /// IT IS NOT AN ARRAY
}

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

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

我用的是这行代码:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}