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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4775722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:02:14  来源:igfitidea点击:

How to check if an object is an array?

javascriptarraysjavascript-objects

提问by mpen

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item, so I can loop over it without fear of an error.

我正在尝试编写一个接受字符串列表或单个字符串的函数。如果它是一个字符串,那么我想将它转换为一个只有一项的数组,这样我就可以循环遍历它而不必担心出错。

So how do I check if the variable is an array?

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



I've rounded up the various solutions below and created a jsperf test. They're all fast, so just use Array.isArray-- it's well-supportednow and works across frames.

我收集了下面的各种解决方案并创建了一个jsperf test。它们都很快,所以只需使用Array.isArray——它现在得到很好的支持并且可以跨帧工作

采纳答案by Fela Winkelmolen

In modern browsers you can do

在现代浏览器中,您可以这样做

Array.isArray(obj)

(Supported byChrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

Chrome 5、Firefox 4.0、IE 9、Opera 10.5 和 Safari 5 支持)

For backward compatibility you can add the following

为了向后兼容,您可以添加以下内容

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

If you use jQuery you can use jQuery.isArray(obj)or $.isArray(obj). If you use underscore you can use _.isArray(obj)

如果您使用 jQuery,您可以使用jQuery.isArray(obj)$.isArray(obj)。如果您使用下划线,您可以使用_.isArray(obj)

If you don't need to detect arrays created in different frames you can also just use instanceof

如果您不需要检测在不同帧中创建的数组,您也可以使用 instanceof

obj instanceof Array

回答by user113716

The method given in the ECMAScript standard to find the class of Object is to use the toStringmethod from Object.prototype.

ECMAScript 标准中给出的寻找 Object 类的toString方法是使用来自的方法Object.prototype

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' );
}

Or you could use typeofto test if it is a String:

或者你可以typeof用来测试它是否是一个字符串:

if( typeof someVar === 'string' ) {
    someVar = [ someVar ];
}

Or if you're not concerned about performance, you could just do a concatto a new empty Array.

或者如果你不关心性能,你可以concat对一个新的空数组做 a 。

someVar = [].concat( someVar );

There's also the constructor which you can query directly:

还有你可以直接查询的构造函数:

if (somevar.constructor.name == "Array") {
    // do something
}


Check out a thorough treatmentfrom @T.J. Crowder'sblog, as posted in his comment below.

检查出一个彻底的治疗@TJ克罗德的博客,张贴在下面他的评论。

Check out this benchmarkto get an idea which method performs better: http://jsben.ch/#/QgYAV

查看此基准测试以了解哪种方法性能更好:http: //jsben.ch/#/QgYAV

From @Bharathconvert string to array using Es6 for the question asked:

@Bharath使用Es6将字符串转换为数组以解决所提出的问题:

const convertStringToArray = (object) => {
   return (typeof object === 'string') ? Array(object) : object 
}

suppose:

认为:

let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']

回答by ChaosPandion

I would first check if your implementation supports isArray:

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

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

You could also try using the instanceofoperator

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

v instanceof Array

回答by janr

jQuery also offers an $.isArray()method:

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>

回答by shinobi

This is the fastest among all methods (all browsers supported):

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

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

回答by Alireza

Imagine you have this array below:

想象一下你有下面这个数组

var arr = [1,2,3,4,5];

Javascript (new and older browsers):

Javascript(新旧浏览器):

function isArray(arr) {
  return arr.constructor.toString().indexOf("Array") > -1;
}

or

或者

function isArray(arr) {
  return arr instanceof Array;
}

or

或者

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}

then call it like this:

然后像这样调用它:

isArray(arr);

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

jQuery:

jQuery:

$.isArray(arr);

Angular:

角度:

angular.isArray(arr);

Underscore and Lodash:

下划线和 Lodash:

_.isArray(arr);

回答by CruorVult

Array.isArray works fast, but it isn't supported by all versions of browsers. So you could make an exception for others and use universal method:

Array.isArray 运行速度很快,但并非所有版本的浏览器都支持它。所以你可以为其他人破例并使用通用方法:

    Utils = {};    
    Utils.isArray = ('isArray' in Array) ? 
        Array.isArray : 
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }

回答by MidnightTortoise

Simple function to check this:

检查这个的简单功能:

function isArray(object)
{
    return object.constructor === Array;
}

回答by ajax333221

As MDN says in here:

正如 MDN在这里所说:

use Array.isArrayor Object.prototype.toString.callto differentiate regular objects from arrays

使用Array.isArrayObject.prototype.toString.call来区分常规对象和数组

Like this:

像这样:

  • Object.prototype.toString.call(arr) === '[object Array]', or

  • Array.isArray(arr)

  • Object.prototype.toString.call(arr) === '[object Array]', 或者

  • Array.isArray(arr)

回答by Vikash Kumar

There's just one line solution for this question

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

x instanceof Array

where x is the variable it will return true if x is an array and false if it is not.

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