Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a variable is an array

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?

like image 963
stpe Avatar asked Jun 29 '09 13:06

stpe


People also ask

How do you know if a variable is an array?

isArray(variableName) method to check if a variable is an array. The Array. isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false .

How do I check if a variable is an array in TypeScript?

You can use the Array. isArray method to check if a value is an array in TypeScript. Copied! The method takes a value as a parameter and returns a boolean result - true if the value is an array and false otherwise.

How do you check if a variable is in an array Python?

To check if an array contains an element or not in Python, use the in operator. The in operator checks whether a specified element is an integral element of a sequence like string, array, list, tuple, etc.


2 Answers

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;     } } 
like image 200
Christoph Avatar answered Sep 21 '22 11:09

Christoph


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.

like image 28
Andy E Avatar answered Sep 18 '22 11:09

Andy E