如何检查对象是否为数组?

JavaScript

Davaid阿飞

2020-03-09

我正在尝试编写一个接受字符串列表或单个字符串的函数。如果它是一个字符串,那么我想将其转换为仅包含一项的数组,因此我可以遍历它而不必担心错误。

那么,如何检查变量是否为数组?


我整理了以下各种解决方案,并创建了jsperf测试它们都非常快,因此只需使用Array.isArray- 现在得到很好的支持,并且可以跨框架使用

第175篇《如何检查对象是否为数组?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

15个回答
Harry逆天Eva 2020.03.09

In your case you may use concat method of Array which can accept single objects as well as array (and even combined):

function myFunc(stringOrArray)
{
  var arr = [].concat(stringOrArray);

  console.log(arr);

  arr.forEach(function(item, i)
  {
    console.log(i, "=", item);
  })
}

myFunc("one string");

myFunc(["one string", "second", "third"]);

concat seems to be one of the oldest methods of Array (even IE 5.5 knows it well).

L西里 2020.03.09

If the only two kinds of values that could be passed to this function are a string or an array of strings, keep it simple and use a typeof check for the string possibility:

function someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
}
Jnck 2020.03.09
A = [1,2,3]
console.log(A.map==[].map)

In search for shortest version here is what I got so far.

Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.

Tony樱番长 2020.03.09

You could is isArray method but I would prefer to check with

Object.getPrototypeOf(yourvariable) === Array.prototype

米亚小哥斯丁 2020.03.09

I know, that people are looking for some kind of raw javascript approach. But if you want think less about, take a look here: http://underscorejs.org/#isArray

_.isArray(object) 

Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
StafanGO 2020.03.09

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Array/isArray

Array.isArray = Array.isArray || function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
};
小胖十三 2020.03.09

您可以检查变量的类型是否为数组;

var myArray=[];

if(myArray instanceof Array)
{
....
}
Eva梅村村 2020.03.09

考虑到以下评论,这是我尝试改进此答案的尝试

var isArray = myArray && myArray.constructor === Array;

它摆脱了if / else,并考虑了数组为null或undefined的可能性

阿飞小卤蛋 2020.03.09

我将提供一个功能来测试您要处理的对象的类型...

function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }

// tests
console.log(
  whatAmI(["aiming","@"]),
  whatAmI({living:4,breathing:4}),
  whatAmI(function(ing){ return ing+" to the global window" }),
  whatAmI("going to do with you?")
);

// output: Array Object Function String

那么您可以编写一个简单的if语句...

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}
村村猴子 2020.03.09

我用一种非常简单的方式来做。为我工作。有什么缺点吗?

Array.prototype.isArray = true;

a=[]; b={};
a.isArray  // true
b.isArray  // (undefined -> false)
小小神无 2020.03.09

这个问题只有一种解决方案

x instanceof Array

其中x是变量,如果x是数组,它将返回true,否则返回false。

6的不行 2020.03.09

简单的功能检查一下:

function isArray(object)
{
    return object.constructor === Array;
}
Harry泡芙 2020.03.09

这是所有方法中最快的方法(支持所有浏览器):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
MonsterKK梅 2020.03.09

jQuery还提供了一种$.isArray()方法:

var a = ["A", "AA", "AAA"];

if($.isArray(a)) {
  alert("a is an array!");
} else {
  alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Tom老丝Pro 2020.03.09

我将首先检查您的实现是否支持isArray

if (Array.isArray)
    return Array.isArray(v);

您也可以尝试使用instanceof运算符

v instanceof Array

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android