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 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

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
  • 10,149
  • 6
  • 29
  • 40
4

check the constructor:

[].constructor == Array  //true
{}.constructor == Object  //true
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
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
  • 26,885
  • 12
  • 107
  • 96
0

This is pretty simple. Try something like

var to = {}.toString;
alert(to.call([])); //[object Array]
alert(to.call({})); //[object Object]
Martin.
  • 10,494
  • 3
  • 42
  • 68