How to detect if a variable is an array

JavascriptArrays

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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;
    }
}

Solution 2 - Javascript

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 7 and lower, because Object.prototype.toString called on an array from a different window will return [object Object], not [object Array]. IE 9 appears to have regressed to this behaviour also (see updated fix below).

If you want a solution that works across all browsers, you can use:

(function () {
    var toString = Object.prototype.toString,
        strArray = Array.toString(),
        jscript  = /*@cc_on @_jscript_version @*/ +0;

    // jscript will be 0 for browsers other than IE
    if (!jscript) {
        Array.isArray = Array.isArray || function (obj) {
            return toString.call(obj) == "[object Array]";
        }
    }
    else {
        Array.isArray = function (obj) {
            return "constructor" in obj && String(obj.constructor) == strArray;
        }
    }
})();

It's not entirely unbreakable, but it would only be broken by someone trying hard to break it. It works around the problems in IE7 and lower and IE9. The bug still exists in IE 10 PP2, but it might be fixed before release.

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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)

Solution 5 - Javascript

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;
}

Solution 6 - Javascript

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] );
        }
    })
}

Solution 7 - Javascript

Why not just use

Array.isArray(variable)

it is the standard way to do this (thanks Karl)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

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();
}

Solution 12 - Javascript

Replace Array.isArray(obj) by obj.constructor==Array

samples :

Array('44','55').constructor==Array return true (IE8 / Chrome)

'55'.constructor==Array return false (IE8 / Chrome)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstpeView Question on Stackoverflow
Solution 1 - JavascriptChristophView Answer on Stackoverflow
Solution 2 - JavascriptAndy EView Answer on Stackoverflow
Solution 3 - JavascriptNosrednaView Answer on Stackoverflow
Solution 4 - JavascriptMario MengerView Answer on Stackoverflow
Solution 5 - JavascriptrazzedView Answer on Stackoverflow
Solution 6 - JavascriptJames HugardView Answer on Stackoverflow
Solution 7 - JavascriptDaniel Worthington-BodartView Answer on Stackoverflow
Solution 8 - JavascriptOtto AllmendingerView Answer on Stackoverflow
Solution 9 - JavascriptEinekiView Answer on Stackoverflow
Solution 10 - JavascriptTony MillerView Answer on Stackoverflow
Solution 11 - JavascriptkuyView Answer on Stackoverflow
Solution 12 - Javascriptpatrick72View Answer on Stackoverflow