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?

Community
  • 1
  • 1
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript – Anders Jul 23 '12 at 22:51
  • zepto.js (has good source code) uses instanceof: `function isArray(value) { return value instanceof Array }` [src](https://github.com/madrobby/zepto/blob/master/src/zepto.js) – bokonic Jul 23 '12 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. – Anmol Saraf Jul 24 '12 at 19:43

4 Answers4

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);
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
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...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    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". – Neil Jul 23 '12 at 23:22
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/

Silver Gonzales
  • 694
  • 5
  • 6
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
Anmol Saraf
  • 15,075
  • 10
  • 50
  • 60