I personally like Peter's suggestion: https://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray()
)
Comments on the post indicate, however, that if toString()
is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString()
has not been changed, and there are no problems with the objects class attribute ([object Array]
is the class attribute of an object that is an array), then I recommend doing something like this:
//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]')
{
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
}
else
{
// may want to change return value to something more desirable
return -1;
}
}
Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray()
is implemented using Object.prototype.toString.call()
in ECMAScript 5. Also note that if you're going to worry about toString()
's implementation changing, you should also worry about every other built in method changing too. Why use push()
? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString()
changing, but I believe the check is unnecessary.