1

Possible Duplicate:
How to detect if a variable is an array

When I need to test if variable is an array (for example input argument in a function that could be object or array) I usually use this piece of code

typeof(myVar) === 'object' && myVar.length !== undefined;

Is this the correct way or is there a more efficient way, considering that even if myVar instanceof Array is faster it should be avoided due to iframe problem?

3
  • stackoverflow.com/questions/767486/… Commented Jul 23, 2012 at 22:51
  • zepto.js (has good source code) uses instanceof: function isArray(value) { return value instanceof Array } src Commented Jul 23, 2012 at 22:52
  • @bokonic : The answer in the possible duplicate clearly tells that this will fail if the object is passed across frame boundaries as each frame has its own Array object. Commented Jul 24, 2012 at 19:43

4 Answers 4

6

Array.isArray is now available with ECMAScript 5, so you can use it with a polyfill for older browsers:

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

Array.isArray(myVar);
Sign up to request clarification or add additional context in comments.

Comments

0

The "iframe problem` can be avoided simply by not using the same name for a frame and for an array. Not hard to do, in my opinion. That said, I've never had a need to assert whether or not something is an array...

1 Comment

The "iframe problem" is that an array created in an iframe is only instanceof the Array constructor of the iframe in which it was created, so if you pass it between frames then instanceof "fails".
0

If you are already using jQuery within your code, you may use jQuery.isArray(). Here is the documentation:

http://api.jquery.com/jQuery.isArray/

Comments

0

You can try - Object.prototype.toString.call
An example -

var a = [1,2]
console.log(Object.prototype.toString.call(a))

This returns [object Array]
which can be checked with string slice method in following way

console.log(Object.prototype.toString.call(a).slice(8,-1)) <br />

which returns "Array"

var a = [1,2]
console.log(Object.prototype.toString.call(a).slice(8,-1) == "Array") // true

4 Comments

or for less overhead you can just compare to the full string: '[object Array]' (like below)
Well I guess Jonathan has already answered this, I must say in a better way :)
Yes you are right Bokonic. I completely agree with you.
One more way to check this is by a.constructor == Array // returns true ( only if a is true array and a is not array-like )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.