Javascript Way To Tell If An Object Is An Array
What's the 'right' way to tell if an object is an Array? function isArray(o) { ??? }
Solution 1:
The best way:
functionisArray(obj) {
returnObject.prototype.toString.call(obj) == '[object Array]';
}
The ECMAScript 5th Edition Specification defines a method for that, and some browsers, like Firefox 3.7alpha, Chrome 5 Beta, and latest WebKit Nightly builds already provide a native implementation, so you might want to implement it if not available:
if (typeofArray.isArray != 'function') {
Array.isArray = function (obj) {
returnObject.prototype.toString.call(obj) == '[object Array]';
};
}
Solution 2:
You should be able to use the instanceof
operator:
var testArray = [];
if (testArray instanceofArray)
...
Solution 3:
jQuery solves lots of these sorts of issues:
jQuery.isArray(obj)
Solution 4:
This is what I use:
functionis_array(obj) {
return (obj.constructor.toString().indexOf("Array") != -1)
}
Solution 5:
function typeOf(obj) {
if ( typeof(obj) == 'object' )
if (obj.length)
return'array';
elsereturn'object';
} elsereturntypeof(obj);
}
Post a Comment for "Javascript Way To Tell If An Object Is An Array"