0

I want to know the type of the variable put in the function. So, I used typeof and like this:

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

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

So, how I can I separate them? Is there any difference between them?

Derek 朕會功夫
  • 88,688
  • 41
  • 174
  • 241

4 Answers4

6

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]';
}
Joe Alfano
  • 9,889
  • 6
  • 27
  • 40
3

check the constructor:

[].constructor == Array  //true
{}.constructor == Object  //true
Dr.Molle
  • 115,009
  • 15
  • 189
  • 197
1

Since ECMAScript 5 you can use the native method:

Array.isArray( maybeArray );

If compatibility is of concern you can use Underscore.js or jQuery:

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

This kind of utility is also present in AngularJS.

Andrejs
  • 25,467
  • 11
  • 103
  • 92
0

This is pretty simple. Try something like

var to = {}.toString;
alert(to.call([])); //[object Array]
alert(to.call({})); //[object Object]
Martin.
  • 10,271
  • 3
  • 40
  • 67