简体   繁体   English

如何判断它是对象还是数组?

[英]How can I tell if it is an object or an array?

I want to know the type of the variable put in the function. 我想知道函数中变量的类型。 So, I used typeof and like this: 所以,我使用typeof ,就像这样:

randomFunctionName: function(obj){
    switch(typeof obj){
        case "object":
           //Something
        case "text":
            //Something else
    }
}

But the problem is, I can't tell if obj is an array or an object, since 但是问题是,我无法判断obj是数组还是对象,因为

typeof [] === "object"  //true
typeof {} === "object"  //true

So, how I can I separate them? 那么,我如何将它们分开? Is there any difference between them? 它们之间有什么区别吗?

An array is an object. 数组是一个对象。 You can test if an object is an array as follows: 您可以测试对象是否为数组,如下所示:

Object.prototype.toString.apply(value) === '[object Array]';

You can wrap this up into a function as follows: 您可以将其包装为一个函数,如下所示:

function isArray(a)
{
    return Object.prototype.toString.apply(a) === '[object Array]';
}

check the constructor: 检查构造函数:

[].constructor == Array  //true
{}.constructor == Object  //true

Since ECMAScript 5 you can use the native method: 从ECMAScript 5开始,您可以使用本机方法:

Array.isArray( maybeArray );

If compatibility is of concern you can use Underscore.js or jQuery : 如果需要考虑兼容性,则可以使用Underscore.jsjQuery

_.isArray( maybeArray ); // will use the native method if available
$.isArray( maybeArray );

This kind of utility is also present in AngularJS. AngularJS中也存在这种实用程序。

This is pretty simple. 这很简单。 Try something like 尝试类似

var to = {}.toString;
alert(to.call([])); //[object Array]
alert(to.call({})); //[object Object]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM