如何确定某物是数组还是物件?

问题描述:

数组和对象是唯一的输入。有一个简单的函数可以确定一个变量是一个数组还是对象?如何确定某物是数组还是物件?

+1

你检查过了吗? - http://stackoverflow.com/questions/8834126/how-to-efficiently-check-if-variable-is-array-or-object-in-nodejs-v8 –

+0

http://blog.niftysnippets.org/2010 /09/say-what.html ..值得看看 – alwaysLearn

我怀疑还有许多其他类似的答案,但是这是一个办法:

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 
... 
+0

+1,但是你应该使用'Object.prototype.toString'作为全局/窗口对象的'toString'方法可能不会产生适当的结果。 :-) – RobG

+0

我想这取决于你需要多少浏览器支持。这应该适用于现代浏览器AFAIK。它默认为'window.toString'这是一个对象。否则,我更喜欢'{} .toString'。但你是对的。 – elclanrs

+0

在Firefox中,'window.toString.call(obj)'返回'[xpconnect包装的本机原型]'。请注意,'window'是一个宿主对象,因此不必遵守本地对象的规则。此外,[global object](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1)不是Object的一个实例(它没有'[[Prototype]]由ECMA-262定义的属性),它是一个存在于其他任何其他对象之前的特殊对象。 – RobG

(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 
} 
+0

如果对象在框架中传递时失败,因为它将从Array和Object的不同实例创建。 – RobG