views:

2031

answers:

4

I would like to check whether a variable is either an array or a single value in JavaScript.

I have found a possible solution...

if (variable.constructor == Array)...

Is this the best way this can be done?

+9  A: 

You could also use:

if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

Brett Bender
I suggest, actually insist on sticking with this "instanceof" operator if you are not working with multiple frames. This is the right way of checking the object type.
BYK
+4  A: 

Via Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

Hank Gay
+4  A: 

There are multiple solutions with all their on quirks. This page gives a good overview. One possible solution is:

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}
Peter Smit
Come on, that method is so, well, unappropriate.
BYK
If you read carefully, it says this method is needed when you are working with mult-frame documents which, is not recommended. This method can easly borke on a little change in the "toString" function.
BYK
Therefor the link is given so that Brett can check them out and see in which case his function has to work
Peter Smit
But when you read your answer, it looks like that method is the best, overall. This is why I warned ;)
BYK
+1  A: 

I noticed someone mentioned about JQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.

JQuery implements it as Peter suggests...

isArray: function( obj ) {
    return toString.call(obj) === "[object Array]";
},

Having put a lot of faith in JQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.

Many thanks for the suggestions.

Andy McCluggage