【发布时间】:2013-04-16 04:15:15
【问题描述】:
数组和对象是唯一的输入。有没有简单的函数可以判断一个变量是数组还是对象?
【问题讨论】:
-
你检查过这个吗? - stackoverflow.com/questions/8834126/…
标签: javascript arrays object
数组和对象是唯一的输入。有没有简单的函数可以判断一个变量是数组还是对象?
【问题讨论】:
标签: javascript arrays object
我怀疑还有许多其他类似的答案,但这是一种方法:
if ({}.toString.call(obj) == '[object Object]') {
// is an object
}
if ({}.toString.call(obj) == '[object Array]') {
// is an array
}
这可以变成一个漂亮的功能:
function typeOf(obj) {
return {}.toString.call(obj).match(/\w+/g)[1].toLowerCase();
}
if (typeOf(obj) == 'array') ...
这适用于任何类型:
if (typeOf(obj) == 'date') // is a date
if (typeOf(obj) == 'number') // is a number
...
【讨论】:
Object.prototype.toString,因为全局/窗口对象的toString 方法可能不会产生适当的结果。 :-)
window.toString,它是一个对象。否则我更喜欢{}.toString。但你是对的。
window.toString.call(obj) 返回[xpconnect wrapped native prototype]。请注意,window 是一个宿主对象,因此不必遵守本机对象的规则。此外,global object 不是 Object 的实例(它也没有 ECMA-262 定义的[[Prototype]] 属性),它是一个先于其他对象存在的特殊对象。
({}).toString 轻松解决的问题。我一直在使用window.toString,在我需要定位的浏览器中没有问题,但我发现了问题。
(variable instanceof Array) 将为数组返回 true。
您也可以使用variable.isArray(),但旧版浏览器不支持。
【讨论】:
你可以使用Array.isArray():
if(Array.isArray(myVar)) {
// myVar is an array
} else {
// myVar is not an array
}
只要你知道它会是一个或另一个,你就已经设置好了。否则,将其与typeof 结合使用:
if(typeof myVar === "object") {
if(Array.isArray(myVar)) {
// myVar is an array
} else {
// myVar is a non-array object
}
}
【讨论】:
先判断是否为 instanceof数组,再判断是否为对象类型。
if(variable instanceof Array)
{
//this is an array. This needs to the first line to be checked
//as an array instanceof Object is also true
}
else if(variable instanceof Object)
{
//it is an object
}
【讨论】: