Anil Namde
Anil Namde

Reputation: 6608

How to check that value is an array?

Is there a good built-in way that I can find whether value is a array or not?

One simple check I can think of is as follows, but I don't like it:

if(ele.push){ /* its array it has push method */ }

I mean i would like know if something like pseudo-code below exists. typeof doesn't seems to be applicable, as it only returns "object" (though that makes sense).

function x(ele){ if(isArray(ele)){ /* dosomething() */ } }

Upvotes: 0

Views: 426

Answers (3)

dreadwail
dreadwail

Reputation: 15409

Not the cleanest but...

function isArray(obj) {
    return obj.constructor == Array;
}

Upvotes: 0

Pepper
Pepper

Reputation: 3022

http://www.andrewpeace.com/javascript-is-array.html

<script type="text/javascript">
  function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
  }
</script>

Upvotes: 2

Matchu
Matchu

Reputation: 85802

element.constructor == Array

Upvotes: 0

Related Questions