views:

155

answers:

6

Hello all,

I have a simple question:

How do I detect if a parameter passed to my javascript function is an array? I don't believe that I can test:

if (typeof paramThatCouldBeArray == 'array') 

So is it possible?

How would I do it?

Thanks in advance.

A: 

You can test the constructor property:

if (param.constructor == Array) {
    ...
}

Though this will include objects that have an array prototype,

function Stack() {
}
Stack.prototype = [];

unless they also define constructor:

Stack.prototype.constructor = Stack;

or:

function Stack() {
    this.constructor = Stack;
}
outis
A: 

I found this here:

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

also this one

function isArray(obj) {
    return (obj.constructor.toString().indexOf(”Array”) != -1);
}
GerManson
+3  A: 
if (param instanceof Array)
    ...
Casey Hope
Good for most cases, but it wont work on cross-frame environments, give a look to this [article](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/).
CMS
+4  A: 

This is the approach jQuery 1.4.2 uses:

var toString = param.prototype.toString;
var isArray = function(obj) {
        return toString.call(obj) === "[object Array]";
    }
James Westgate
+1  A: 

Some days ago I was building a simple type detection function, maybe its useful for you:

Usage:

//...
if (typeString(obj) == 'array') {
  //..
}

Implementation:

function typeString(o) {
  if (typeof o != 'object')
    return typeof o;

  if (o === null)
      return "null";
  //object, array, function, date, regexp, string, number, boolean, error
  var internalClass = Object.prototype.toString.call(o)
                                               .match(/\[object\s(\w+)\]/)[1];
  return internalClass.toLowerCase();
}

The second variant of this function is more strict, because it returns only object types described in the ECMAScript specification (possible output values: "object", "undefined", "null", and "function", "array", "date", "regexp", "string", "number", "boolean" "error", using the [[Class]] internal property).

CMS
A: 

Duck Typying

Actually, you don't necessarily want to check that an object is an array. You should duck type it and the only thing you want that object to implement is the length property. After this you can transform it into an array:

var arrayLike = {
    length : 3,

    0: "foo"
};

// transform object to array
var array = Array.prototype.slice.call(arrayLike);

JSON.stringify(array); // ["foo", null, null]

Array.prototype.slice.call(object) will transform into an array every object that exposes a length property. In the case of strings for example:

var array = Array.prototype.slice.call("123");
JSON.stringify(array); // ["1", "2", "3"]

Well, this technique it's not quite working on IE6 (I don't know about later versions), but it's easy to create a small utility function to transform objects in arrays.

Ionuț G. Stan