How should I detect if the argument is an array because typeof [] returns 'object' and I want to distinguish between arrays and objects.

It is possible that object will look like {"0":"string","1":"string","length":"2"} but I don't want it to come out as an array if it is in fact an object looking like an array.

JSON.parse and JSON.stringify are able to make this distinction. How can I do it?

I am using Node.JS which is based on V8 the same as Chrome.

share|improve this question

feedback

4 Answers

up vote 9 down vote accepted
  • Array.isArray

native V8 function. It's fast, it's always correct. This is part of ES5.

  • arr instanceof Array

Checks whether the object was made with the array constructor.

A method from underscore. Here is a snippet taken from the their source

var toString = Object.prototype.toString,
    nativeIsArray = Array.isArray;
_.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
};

This method takes an object and calls the Object.prototype.toString method on it. This will always return [object Array] for arrays.

In my personal experience I find asking the toString method is the most effective but it's not as short or readable as instanceof Array nor is it as fast as Array.isArray but that's ES5 code and I tend to avoid using it for portability.

I would personally recommend you try using underscore, which is a library with common utility methods in it. It has a lot of useful functions that DRY up your code.

share|improve this answer
@GeorgeBailey rephrased properly. underscore is a useful library that implements these methods and it generally always implements them in the best manner. – Raynos May 9 '11 at 20:01
feedback
Array.isArray(argument)

(funny: body must be at least 30 characters; you entered 23)

share|improve this answer
+1: Consistent with Node.JS Buffer.isBuffer. – George Bailey May 9 '11 at 20:04
feedback

Taken from http://developer.yahoo.com/yui/docs/Lang.js.html

function isArray (o) {
  return Object.prototype.toString.apply(o) === '[object Array]';
}
share|improve this answer
feedback

How about:

your_object instanceof Array

In V8 in Chrome I get

[] instanceof Array
> true
({}) instanceof Array
> false 
({"0":"string","1":"string","length":"2"}) instanceof Array
> false
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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