如何在JavaScript中检查变量是否为数组?
if (variable.constructor == Array)
如何在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([]);
其他回答
通过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提到的主要失败是无法正确确定在不同上下文(例如窗口)中创建的数组。如果这还不够的话,该页面有一个更复杂的版本。
我注意到有人提到jQuery,但我不知道有isArray()函数。原来它是在1.3版中添加的。
jQuery按照Peter的建议实现它:
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
我已经对jQuery很有信心(尤其是他们的跨浏览器兼容性技术),我要么升级到1.3版并使用他们的功能(前提是升级不会导致太多问题),要么直接在代码中使用建议的方法。
非常感谢您的建议。
我在这里尝试了大多数解决方案。但没有一个有效。然后我提出了一个简单的解决方案。希望它能帮助某人并节省他们的时间。
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]';
}
您还可以使用:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
在我看来,这是一个非常优雅的解决方案,但对每个人来说都是自己的。
编辑:
截至ES5,现在还有:
Array.isArray(value);
但这将在旧浏览器上打破,除非您使用的是polyfills(基本上…IE8或类似)。