Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: detect if argument is array instead of object (Node.JS)

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.

like image 802
700 Software Avatar asked May 09 '11 19:05

700 Software


People also ask

How do you check if an object is an array or not in node JS?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

How do you check if a variable is an object or array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

How can you tell the difference between an array and an object in JavaScript?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

Is typeof an array?

You shouldn't use the typeof operator to check whether a value is an array, because typeof cannot distinguish between arrays and objects. Instead you should use Array. isArray() , because typeof would return 'object' , not 'array' . Array.


1 Answers

  • 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.

  • _.isArray // underscore method.

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.

like image 155
Raynos Avatar answered Oct 13 '22 04:10

Raynos