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

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

其他回答

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

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

Array.prototype.isArray = true;

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

var box = doSomething();

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

isArray仅在其为数组时可用

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

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

在现代浏览器(以及一些传统浏览器)中,您可以

Array.isArray(obj)

(支持Chrome 5、Firefox 4.0、IE 9、Opera 10.5和Safari 5)

如果需要支持旧版本的IE,可以使用es5垫片来polyfill Array.isArray;或添加以下内容

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

如果使用jQuery,可以使用jQuery.isArray(obj)或$.isArra(obj

如果不需要检测在不同帧中创建的数组,也可以只使用instanceof

obj instanceof Array

注意:可以用于访问函数参数的arguments关键字不是Array,尽管它(通常)的行为类似于:

var func=函数(){console.log(参数)//[1,2,3]console.log(arguments.length)//3console.log(Array.isArray(参数))//false!!!console.log(argument.slice)//未定义(Array.prototype方法不可用)console.log([3,4,5].slice)//函数slice(){[本机代码]}}函数(1,2,3)

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

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]

我刚想到的:

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