1

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?

6

5 Answers 5

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]';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is [object Array] the same in every browser?
Yes, this will work for any browser that is ECMAScript compliant, which should be all browsers.
5

check the constructor:

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

5 Comments

{}.constructor --> SyntaxError: Unexpected token .
I see the image but I don't get the error in chrome(the image looks like chrome)
I am using Chrome 20.0.1115.1 Do you think it is a bug of Chrome or did I do something wrong?
The latest version I can get (winXP) is 18.0.1025.162 m and i don't get any error. chrome19 is BETA and chrome20 is dev, so I don't have do care about them because they don't have to be stable.
I am actually using the dev channel, but I don't think that will affect JavaScript?
3

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.

Comments

1

This is pretty simple. Try something like

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

Comments

0

I would suggest, based on @Martin's answer:

// tests whether value is an object with curly braces 
// (Arrays are objects too, but we don't want to include them)
const isAnObjectObject = (value) => {
     return value.toString() === "[object Object]" && value !== "[object Object]"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.