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

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

It is possible that the object will look like {"0":"string","1":"string","length":"2"} , but I do not want it to come out as an array if it is actually an object, like an array.

JSON.parse and JSON.stringify can make this difference. How can i do this?

I use Node.JS, which is based on V8 just like Chrome.

+58
javascript object arrays typeof
May 09 '11 at 19:46
source share
5 answers
  • Array.isArray

built-in V8 function. It's fast, it's always right. This is part of ES5.

  • arr instanceof Array

Checks if an object was created using an array constructor.

The method of underlining. Here is a snippet taken from 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 believe that the toString method is the most efficient, but it is not as short and cannot be read as instanceof Array , but it is not as fast as Array.isArray , but this code is ES5 and I try to avoid using it for portability.

I personally would recommend using underscore , which is a library with common utilities in it. It has many useful features that DRY makes your code.

+127
May 9 '11 at 19:48
source share

Try this code:

 Array.isArray(argument) 
+41
May 09 '11 at 19:53
source share

What 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 
+5
May 09 '11 at 19:50
source share

This question seems to have some good answers, but for completeness, I would add another option that was not previously proposed.

To check if something is an array, you can use your own Node.js util and its isArray() function.

Example:

 var util = require('util'); util.isArray([]); // true util.isArray(new Array); // true util.isArray({"0":"string","1":"string","length":"2"}); // false 

With this method, you don’t have to worry about the JS standards implemented by V8, as it will always show the correct answer.

+5
Feb 17 '14 at 13:03
source share

Try this way:
console.log (Object.prototype.toString.call (arg) .replace (/ ^ [object (. +)] $ /, '$ 1'). toLowerCase ())

0
Jun 27 '17 at 2:59 on
source share



All Articles