How to detect if a variable is an array

2019-01-02 19:56发布

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?

12条回答
长期被迫恋爱
2楼-- · 2019-01-02 20:13

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] );
        }
    })
}
查看更多
呛了眼睛熬了心
3楼-- · 2019-01-02 20:14

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;
    }
}
查看更多
妖精总统
4楼-- · 2019-01-02 20:16

If you are doing this in CouchDB (SpiderMonkey) then use

Array.isArray(array)

as array.constructor === Array or array instanceof Array do not work. Using array.toString() === "[object Array]" does work but seems pretty dodgy in comparison.

查看更多
忆尘夕之涩
5楼-- · 2019-01-02 20:19

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();
}
查看更多
妖精总统
6楼-- · 2019-01-02 20:20

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)

查看更多
十年一品温如言
7楼-- · 2019-01-02 20:20

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;
}
查看更多
登录 后发表回答