JavaScript: detect if argument is array instead of object (Node.JS)
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.
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