JavaScript: 检测参数是否是数组而不是对象(Node.JS)

我应该如何检测参数是否是一个数组,因为 typeof []返回 'object',我想区分数组和对象。

对象可能看起来像 {"0":"string","1":"string","length":"2"},但是如果它实际上是一个看起来像数组的对象,我不希望它以数组的形式出现。

JSON.parseJSON.stringify能够做出这种区分。我该怎么做呢?

我使用的是 Node.JS,它和 Chrome 一样基于 V8。

95045 次浏览
  • 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

Try this code:

Array.isArray(argument)

I looks like this question has several good answers, but for completeness I would add another option, which have not been suggested earlier.

In order to check if something is an array, you can use Node.js util native module 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 that method you do not have to worry about JS standards implemented by V8 as it will always show the right answer.

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