How to detect if a variable is an array
Asked Answered
S

12

115

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?

Sulphathiazole answered 29/6, 2009 at 13:48 Comment(6)
Won't this return true on a string?Genu
The example given is not ment to answer the question itself, is is merely an example of how a solution might be approached - which often fail in special cases (like this one, hence the "However, note...").Sulphathiazole
@James: in most browsers (IE excluded), strings are array-like (ie access via numerical indices is possible)Gains
cant' believe this is so difficult to do...Rust
possible duplicate of How do you check if a variable is an array in JavaScript?Cipher
possible duplicate of Check if object is array?Conation
G
174

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;
    }
}
Gains answered 29/6, 2009 at 14:50 Comment(11)
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.Genu
@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...Gains
@Gains - 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.Genu
@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?Gains
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 :PGenu
@Gains - Will different browsers return different values, such as [object array]? Or if checking for an object, [object object]? Or is this standardized?Cassiodorus
@TravisJ: see ECMA-262 5.1, section 15.2.4.2; internal class names are by convention upper case - see section 8.6.2Gains
"This won't work if the object is passed across frame boundaries as each frame has its own Array object." By Array object you mean window.Array, which is actually a function/object constructor right?Aurelioaurelius
@Hoffmann: correct; in general, window1.Array !== window2.Array which means window1.Array.prototype !== window2.Array.prototype and thus new window1.Array instanceof window2.Array === falseGains
Interesting, so in some rather bizarre circumstances you would actually want to differentiate both objects. For example when you augmented the array prototype in one frame but not in the other.Aurelioaurelius
don't use the [0]-checking solution, you may define a "hybrid" object that has the 0 as an attribute (but is NOT an Array): var a = {0:"hi",b:"aa"}; and then you may run: typeof a[0] - and actually getting: "hi" (so.. not "undefine"). I am using (a bit of overkill..) this one: var type = typeof something; "object" === type ? (something instanceof Array || "[object Array]" === Object.prototype.toString.call(something) ? "array" : type) : type;.Delisadelisle
C
49

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.

Coper answered 27/10, 2010 at 0:14 Comment(9)
The accepted answer does work fine in IE8+, but not in IE6,7Snip
@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.Coper
WAAAAAAA, I hate IE. I totally forgot about the different "document modes", or "schizo modes", as I'm gonna call them.Snip
While the ideas are great and it looks good, this does not work for me in IE9 with popup windows. It returns false for arrays created by the opener... Is there a IE9 compatbile solutions? (The problem seems to be that IE9 implemnets Array.isArray itself, which returns false for the given case, when it should not.Mantegna
@Steffen: interesting, so the native implementation of isArray does not return true from arrays created in other document modes? I'll have to look into this when I get some time, but I think the best thing to do is file a bug on Connect so that it can be fixed in IE 10.Coper
@Steffen: I've filed a bug on Connect and updated my post to work with all versions of IE.Coper
This works for me in IE9 now. Thanks. (Though, I replaced "constructor" in obj with obj.constructor which should be the same, right? I could not find information if all browsers support in...)Mantegna
@Steffen: #2921265 :-)Coper
Although this won't work under IE8 because of lack of Array.isArray, still +1 for @cc_on trick I didn't know :DInoculate
M
8

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.

Mauromaurois answered 29/6, 2009 at 15:0 Comment(2)
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 restrictiveGains
@ Christoph--I added a bit more via an edit. Fascinating topic.Mauromaurois
G
2

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)

Galarza answered 29/6, 2009 at 13:54 Comment(3)
They return false on IE (#2968). (From jquery source)Quezada
That comment in the jQuery source seems to refer to the isFunction function, not isArrayGalarza
you should use Object.prototype.toString() - that's less likely to breakGains
Q
2

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;
}
Quezada answered 29/6, 2009 at 13:59 Comment(3)
The second test would return true for a string as well: typeof "abc".length === "number" // trueLovelady
Plus, I guess you should never hardcode type names, like "number". Try comparing it to the actual number instead, like typeof(obj) == typeof(42)Inordinate
@mtod: why shouldn't type names be hardcoded? after all, the return values of typeof are standardized?Gains
D
2

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

Derrek answered 20/11, 2017 at 14:34 Comment(1)
This works in Node.js and in the browsers too, not just CouchDB: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Phyletic
G
1

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] );
        }
    })
}
Genu answered 29/6, 2009 at 14:21 Comment(5)
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])Gains
@Gains - 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.Genu
@Gains - Why is iterating over arrays with for..in bad[tm]? How else would you iterate over arrays and/or hashtables (objects)?Genu
@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 mindGains
@Gains - 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).Genu
U
0

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

Undercut answered 29/6, 2009 at 13:54 Comment(0)
H
0

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

Hairston answered 29/6, 2009 at 14:46 Comment(8)
using constructor for type checking is imo too brittle; use one of the suggested alternatives insteadGains
why do you think so? About brittle?Leo
@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 arbitrarilyGains
Thanks, found another explanation here: thinkweb2.com/projects/prototype/…Leo
This is not reliable, because the Array object itself can be over-written with a custom object.Cockiness
@Gains - the problem with "instanceof" is that it leaks (big time) when run against COM objects in IE.Genu
@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)?Gains
@Kamarey, link is now broken, thinkweb2.com doesn't resolve. Removing the 2 just gets you a 404 from thinkweb.com.Musty
P
-2

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.

Purview answered 29/6, 2009 at 13:56 Comment(0)
Q
-2

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();
}
Quaky answered 29/6, 2009 at 16:12 Comment(1)
fooled by {constructor:{toString:function(){ return "function Array() { [native code] }"; }}}Conation
F
-4

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)

File answered 3/3, 2015 at 17:5 Comment(1)
Why would you replace to correct function with a horrible one?Conation

© 2022 - 2024 — McMap. All rights reserved.