As far as I know there are three ways of finding out if an object is an Array
by isArray
function if implemented
Array.isArray()
If what you're trying to do is to decide whether a parameter passed to you is an array that you should iterate over, there's a fair amount of code out there that just looks for a .length
attribute and treats as an array or a pseudo-array if that attribute is present.
This is because there are lots of things that aren't actually arrays (but are pseudo arrays with array like capabilities) that you may want your code to treat like an array. Examples of some of these kinds of things are a jQuery object or a nodeList returned from many DOM calls. Here's a code example:
// accepts:
// single DOM element
// array of DOM elements
// nodeList as returned from various DOM functions like getElementsByClassName
// any array like object with a .length attribute and items in numeric indexes from 0 to .length-1 like a jQuery object
function hideElements(input) {
if (input.length !== undefined) {
for (var i = 0, len = input.length; i < len; i++) {
input[i].style.display = "none";
}
} else {
input.style.display = "none";
}
return(input);
}
The jQuery .each()
function also just tests the parameter passed to it for .length (and verifying that it's not a function) before deciding it's something it should iterate like an array.
If that isn't the problem you're trying to solve, I can find two references to using the first technique: