Testing if an element is an array in Javascript

To check if an element is an array in JavaScript, I always used the Crockford function (page 61 of โ€œThe Good Partsโ€):

var is_array = function (value) { return value && typeof value === 'object' && typeof value.length === 'number' && typeof value.splice === 'function' && !(value.propertyIsEnumerable('length')); } 

But if I'm not mistaken, recently some guy from Google found a new way to test the JavaScript array, but I just canโ€™t remember where I read it from and how the function went.

Can someone please point me to his decision please?


[Update]
The person from Google who apparently discovered this is called Mark Miller .

Now I also read that from this post that his solution can also easily break:

 // native prototype overloaded, some js libraries extends them Object.prototype.toString= function(){ return '[object Array]'; } function isArray ( obj ) { return Object.prototype.toString.call(obj) === '[object Array]'; } var a = {}; alert(isArray(a)); // returns true, expecting false; 

So, I ask, is there a way to verify the validity of an array?

+6
javascript arrays
source share
2 answers

I believe what you are looking for

 Object.prototype.toString.call(value) === "[object Array]"; 

This is a method that jQuery uses to test whether the passed parameter value is a function or an array object. There are browser-specific instances where using typeof doesn't give the right result

+6
source share

You can do it:

 t = [1,2]; // Now to check if this is an array if (t.constructor == Array) { alert('t is an array'); } else { alert('t is NOT an array'); } 

Basically, variable.constructor == Array

-one
source share

All Articles