In order to make the syntax for one of my functions nicer, I need to be able to tell whether a specific parameter is an array or \"hash\" (which I know are just objects).
<
You could check the length property as SLaks suggested, but as soon as you pass it a function object you'll be surprised, because it in fact has a length property. Also if the object has a length property defined, you'll get wrong result again.
Your best bet is probably:
function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
}
jQuery uses it, and a "couple of" other people... :)
It is more fail proof than the instanceof way. The method is also suggested by the following article:
'instanceof' considered harmful (or how to write a robust 'isArray') (@kagax)
Another thing to add that this function is almost identical to the Array.isArray
function in ES 5 spec:
15.4.3.2 Array.isArray ( arg )
- If Type(arg) is not Object, return false.
- If the value of the [[Class]] internal property of arg is "Array", then return true.
- Return false.