Cross-browser JavaScript - detecting arrays
written by Craig, 11 October 2007
Checking whether a JavaScript variable is an array is incredibly awkward. Various solutions have been proposed, but just when you think you’ve got the ultimate solution, a particular browser pops up and bites you (yes, Safari, I’m talking about you!)
So why is this particular problem so difficult?
- Arrays are reported as being ‘objects’ - but so are lots of other things.
- Arrays have a length, but so do some DOM nodes (like form elements). Also, simple checks like ‘x.length’ will return false if the length doesn’t exist or if it’s zero.
- Arrays have constructors, but again, so do other things. If you use ‘toString’ on the constructor, most browsers report a function name of ‘Array’ … unfortunately, Safari chooses to return ‘function’.
- Some DOM collections are very similar to arrays, but aren’t!
After much swearing, I’ve finally come up with a solution:
function IsArray(array)
{
return !(
!array ||
(!array.length || array.length == 0) ||
typeof array !== ‘object’ ||
!array.constructor ||
array.nodeType ||
array.item
);
}
// examples
alert( IsArray( [] ) ); // true
alert( IsArray( [1,2,3] ) ); // true
alert( IsArray( {a:1} ) ); // false
alert( IsArray( document.forms[0] ) ); // false
alert( IsArray( [document.forms[0]] ) ); // true
It appears to work consistently in IE5.0+, Firefox, Safari, Opera and Konqueror, but I still have a nagging doubt that I’ve missed something?
Does anyone have anything better?
- categories: javascript
- trackback: http://www.optimalworks.net/blog/2007/web-development/javascript/array-detection/trackback
- bookmark: del.icio.us, digg, facebook, reddit, Furl, Spurl, Blinklist, Slashdot, Technorati, Yahoo!
5 comments:
11 October 2007 steve commented
11 October 2007 steve commented
11 October 2007 Craig commented
11 October 2007 los commented
12 October 2007 Craig commented