views:

1031

answers:

11

What is the best de-facto standard cross-browser method to determine if a variable in JavaScript is an array or not?

Searching the web there are a number of different suggestions, some good and quite a few invalid.

For example, the following is a basic approach:

function isArray(obj) {
    return (obj && obj.length);
}

However, note what happens if the array is empty, or obj actually is not an array but implements a length property, etc.

So which implementation is the best in terms of actually working, being cross-browser and still perform efficiently?

A: 

If you want cross-browser, you want jQuery.isArray.

Otto Allmendinger
-1 Mario's answer (http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array/1058457#1058457) is more complete than this one
Gavin Miller
+2  A: 

jQuery implements an isArray function, which suggests the best way to do this is

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

(snippet taken from jQuery v1.3.2 - slightly adjusted to make sense out of context)

Mario Menger
They return false on IE (#2968). (From jquery source)
razzed
That comment in the jQuery source seems to refer to the isFunction function, not isArray
Mario Menger
you should use `Object.prototype.toString()` - that's less likely to break
Christoph
A: 

One of the best researched and discussed versions of this function can be found on the PHPJS site. You can link to packages or you can go to the function directly. I highly recommend the site for well constructed equivalents of PHP functions in JavaScript.

Tony Miller
+2  A: 

Stealing from the guru John Resig and jquery:

function isArray(array) {
    if ( toString.call(array) === "[object Array]") {
        return true;
    } else if ( typeof array.length === "number" ) {
        return true;
    }
    return false;
}
razzed
The second test would return true for a string as well: typeof "abc".length === "number" // true
Daniel Vandersluis
Plus, I guess you should never hardcode type names, like "number". Try comparing it to the actual number instead, like typeof(obj) == typeof(42)
ohnoes
@mtod: why shouldn't type names be hardcoded? after all, the return values of `typeof` are standardized?
Christoph
A: 

What are you going to do with the value once you decide it is an array?

For example, if you intend to enumerate the contained values if it looks like an array OR if it is an object being used as a hash-table, then the following code gets what you want (this code stops when the closure function returns anything other than "undefined". Note that it does NOT iterate over COM containers or enumerations; that's left as an exercise for the reader):

function iteratei( o, closure )
{
    if( o != null && o.hasOwnProperty )
    {
        for( var ix in seq )
        {
            var ret = closure.call( this, ix, o[ix] );
            if( undefined !== ret )
                return ret;
        }
    }
    return undefined;
}

(Note: "o != null" tests for both null & undefined)

Examples of use:

// Find first element who's value equals "what" in an array
var b = iteratei( ["who", "what", "when" "where"],
    function( ix, v )
    {
        return v == "what" ? true : undefined;
    });

// Iterate over only this objects' properties, not the prototypes'
function iterateiOwnProperties( o, closure )
{
    return iteratei( o, function(ix,v)
    {
        if( o.hasOwnProperty(ix) )
        {
            return closure.call( this, ix, o[ix] );
        }
    })
}
James Hugard
although the answer might be interesting, it doesn't really have anything to do with the question (and btw: iterating over arrays via `for..in` is bad[tm])
Christoph
@Christoph - Sure it does. There must be some reason for deciding if something is an Array: because you want to do something with the values. The most typical things (in my code, at least) are to map, filter, search, or otherwise transform the data in the array.The above function does exactly that: if the thing passed has elements that can be iterated over, then it iterates over them. If not, then it does nothing and harmlessly returns undefined.
James Hugard
@Christoph - Why is iterating over arrays with for..in bad[tm]? How else would you iterate over arrays and/or hashtables (objects)?
James Hugard
@James: `for..in` iterates over enumerable properties of objects; you shouldn't use it with arrays because: (1) it's slow; (2) it isn't guaranteed to preserve order; (3) it will include any user-defined property set in the object or any of its prototypes as ES3 doesn't include any way to set the DontEnum attribute; there might be other issues which have slipped my mind
Christoph
@Christoph - On the other hand, using for(;;) won't work properly for sparse arrays and it won't iterate object properties. #3 is considered bad form for Object due to the reason you mention. On the other hand, you are SO right with regards to performance: for..in is ~36x slower than for(;;) on a 1M element array. Wow. Unfortunatally, not applicable to our main use case, which is iterating object properties (hashtables).
James Hugard
A: 

I suppose Object.constructor is not cross-browser, so I’d try:

function is_array($obj) {
    // if it’s not an object, it’s not an array either!
    if (typeof $obj != 'object') return false;
    // create a random key. avoid collisions
    do {
        var randomKey = 'k' + Math.random();
    } while ((randomKey in $obj) or (randomKey in Array.prototype));

    // ... and a random value
    var randomValue = 'v' + Math.random();

    // attach this key/value pair to *every* array 
    Array.prototype[randomKey] = randomValue;

    // check the existence of random key and value
    var isArray = $obj[randomKey] == randomValue;

    // remove the mess
    delete Array.prototype[randomKey];

    return isArray;
}

There may be, AFAIR, some issues in cross-window coding. Not sure how it works, but I’ve read somewhere, that document.someIframe.contentWindow.Array.prototype may be different than Array.prototype. Please comment if someone is familiar with it.

OTOH, Kevin posted a nice looking answer. It will fail if you have object of class SomeArrayObject or similar and it’s not based on any standard I think (so this behavior could change in the future) its quite clean and simple.

Maciej Łebkowski
A: 

On w3school there is an example that should be quite standard.

To check if a variable is an array they use something similar to this

function arrayCheck(obj) { 
    return obj && (obj.constructor==Array);
}

tested on Chrome, Firefox, Safari, ie7

Eineki
using `constructor` for type checking is imo too brittle; use one of the suggested alternatives instead
Christoph
why do you think so? About brittle?
Kamarey
@Kamarey: `constructor` is a regular DontEnum property of the prototype object; this might not be a problem for built-in types as long as nobody does anything stupid, but for user-defined types it easily can be; my advise: always use `instanceof`, which checks the prototype-chain and doesn't rely on properties which can be overwritten arbitrarily
Christoph
Thanks, found another explanation here:http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
Kamarey
This is not reliable, because the Array object itself can be over-written with a custom object.
Josh Stodola
@Christoph - the problem with "instanceof" is that it leaks (big time) when run against COM objects in IE.
James Hugard
@Josh: but overwriting `window.Array` is almost always stupid, whereas replacing prototypes of non-native objects isn't; so instead of using `constructor` for natives and `instanceof` otherwise, why not always use `instanceof` (memory issues aside)?
Christoph
+24  A: 

Type checking of objects in JS is done via instanceof, ie

obj instanceof Array

This won't work if the object is passed across frame boundaries as each frame has its own Array object. You can work around this by checking the internal [[Class]] property of the object. To get it, use Object.prototype.toString() (this is guaranteed to work by ECMA-262):

Object.prototype.toString.call(obj) === '[object Array]'

Both methods will only work for actual arrays and not array-like objects like the arguments object or node lists. As all array-like objects must have a numeric length property, I'd check for these like this:

typeof obj !== 'undefined' && obj !== null && typeof obj.length === 'number'

Please note that strings will pass this check, which might lead to problems as IE doesn't allow access to a string's characters by index. Therefore, you might want to change typeof obj !== 'undefined' to typeof obj === 'object' to exclude primitives and host objects with types distinct from 'object' alltogether. This will still let string objects pass, which would have to be excluded manually.

In most cases, what you actually want to know is whether you can iterate over the object via numeric indices. Therefore, it might be a good idea to check if the object has a property named 0 instead, which can be done via one of these checks:

typeof obj[0] !== 'undefined' // false negative for `obj[0] = undefined`
obj.hasOwnProperty('0') // exclude array-likes with inherited entries
'0' in Object(obj) // include array-likes with inherited entries

The cast to object is necessary to work correctly for array-like primitives (ie strings).

Here's the code for robust checks for JS arrays:

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

and iterable (ie non-empty) array-like objects:

function isNonEmptyArrayLike(obj) {
    try { // don't bother with `typeof` - just access `length` and `catch`
        return obj.length > 0 && '0' in Object(obj);
    }
    catch(e) {
        return false;
    }
}
Christoph
Great summary of the state-of-the-art in js array-checking.
Nosredna
As of MS JS 5.6 (IE6?), the "instanceof" operator leaked a lot of memory when run against a COM object (ActiveXObject). Have not checked JS 5.7 or JS 5.8, but this may still hold true.
James Hugard
@James: interesting - I didn't know of this leak; anyway, there's an easy fix: in IE, only native JS objects have a `hasOwnProperty` method, so just prefix your `instanceof` with `obj.hasOwnProperty also, is this still an issue with IE7? my simple tests via task manager suggest that the memory got reclaimed after minimizing the browser...
Christoph
@Christoph - Not sure about IE7, but IIRC this was not on the list of bugfixes for JS 5.7 or 5.8. We host the underlying JS engine on the server side in a service, so minimizing the UI is not applicable.
James Hugard
@James: minimizing the UI is just an easy way to trigger garbage collection and other cleanup code; not knowing your environment, I'm not sure if you have any way to do something equivalent; also, `isPrototypeOf()` *seems* to have the same problem as it's basically the same thing (search the prototype chain for a specific object) - could you confirm?
Christoph
Can't duplicate the leak with JS 5.6 on Win2003 w/IE7 (was discovered on Win2000 w/IE6), but ignore at your own peril :P
James Hugard
+3  A: 

Crockford has two answers on page 106 of "The Good Parts." The first one checks the constructor, but will give false negatives across different frames or windows. Here's the second:

if (my_value && typeof my_value === 'object' &&
        typeof my_value.length === 'number' &&
        !(my_value.propertyIsEnumerable('length')) {
    // my_value is truly an array!
}

Crockford points out that this version will identify the arguments array as an array, even though it doesn't have any of the array methods.

His interesting discussion of the problem begins on page 105.

There is further interesting discussion (post-Good Parts) here which includes this proposal:

var isArray = function (o) {
    return (o instanceof Array) ||
        (Object.prototype.toString.apply(o) === '[object Array]');
};

All the discussion makes me never want to know whether or not something is an array.

Nosredna
this will break in IE for strings objects and excludes string primitives, which are array-like except in IE; checking [[Class]] is better if you want actual arrays; if you want array-likes objects, the check is imo too restrictive
Christoph
@ Christoph--I added a bit more via an edit. Fascinating topic.
Nosredna
A: 

Not enough reference equal of constructors. Sometime they have different references of constructor. So I use string representations of them.

function isArray(o) {
    return o.constructor.toString() === [].constructor.toString();
}
kuy
+2  A: 

The arrival of ECMAScript 5th Edition gives us the most sure-fire method of testing if a variable is an array, Array.isArray():

Array.isArray([]); // true

While the accepted answer here will work across frames and windows for most browsers, it doesn't for Internet Explorer, because Object.prototype.toString called on an array from a different window will return [object Object], not [object Array].

I won't go into all the nitty gritty parts of the solution here, if you're interested in that you can read this blog post. However, if you want a solution that works across all browsers, you can use:

(function () {
    var toString = Object.prototype.toString,
        strArray = Array.toString(),
        hasNoClass = false;

    /*@cc_on
        /*@if (@_jscript_version <= 5.7)
            hasNoClass = true;
        /*@end
    @*/

    // hasNoClass will be true for Internet Explorer <= 7 only
    if (hasNoClass) {
        Array.isArray = function (obj) {
            return "constructor" in obj && String(obj.constructor) == strArray;
        }
    }
    else {
        Array.isArray = Array.isArray || function (obj) {
            return toString.call(obj) == "[object Array]";
        }
    }
})();

PS, if you're unsure about the solution then I recommend you test it to your hearts content and/or read the blog post. There are other potential solutions there if you're uncomfortable using conditional compilation.

Andy E
[The accepted answer](http://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array/1058753#1058753) does work fine in IE8+, but not in IE6,7
Pumbaa80
@Pumbaa80: You're right :-) IE8 fixes the problem for its own Object.prototype.toString, but testing an array created in an IE8 document mode that is passed to an IE7 or lower document mode, the problem persists. I had only tested this scenario and not the other way around. I've edited to apply this fix only to IE7 and lower.
Andy E
WAAAAAAA, I hate IE. I totally forgot about the different "document modes", or "schizo modes", as I'm gonna call them.
Pumbaa80