Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

Possible Duplicate:
How do you check if a variable is an array in JavaScript?

How can I check if a variable is an array (so I can handle each arrayvalue) or a single arrayvalue?

share|improve this question

marked as duplicate by mellamokb, Joe, nrabinowitz, Lekensteyn, Quentin Oct 4 '11 at 20:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
also JavaScript: Check if object is array? – mellamokb Oct 4 '11 at 20:51
1  
Next time you might want to try Google before you go to SO... – mellamokb Oct 4 '11 at 20:56
    
@mellamokb LOL why the hell is my question downvoted?! It was about the difference between an array and an arrayvalue. The wanted answer turned out to be a check on what the length of the variable was. Can either I or you undo the downvote? – Olesma Oct 4 '11 at 21:35
    
{Sigh}... probably because there are numerous other questions just like this already been asked. Have an up-vote on the house :-) – mellamokb Oct 4 '11 at 21:46
    
Yes, but none of the suggested duplicates were answered with this elegant solution very useful for my specific problem... Anyway thanks! – Olesma Oct 4 '11 at 21:51
up vote 0 down vote accepted

From the MDN page for isArray which is part of the ECMAScript 5 standard:

if(!Array.isArray) {
  Array.isArray = function (arg) {
    return Object.prototype.toString.call(arg) == '[object Array]';
  };
}

In many cases, you can also just check to see if there is a .length property (this is often what jQuery does) because this will also accept any array-like object that isn't actually an array, but can be iterated like one. Obviously, if you have things that do have a .length property that you don't want treated like an array, this will get fooled by that situation so you have to know which you want:

function isArrayLike(item) {
    return(typeof item.length != "undefined");
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.