你如何检查是否变量是在JavaScript中的数组? [英] How do you check if a variable is an array in JavaScript?

查看:134
本文介绍了你如何检查是否变量是在JavaScript中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查变量是否是数组或JavaScript中的单个值。

I would like to check whether a variable is either an array or a single value in JavaScript.

我发现了一个可能的解决方案...

I have found a possible solution...

if (variable.constructor == Array)...

这是可以做到这一点的最好方法是什么?

Is this the best way this can be done?

推荐答案

有检查,如果一个变量是一个数组与否的几种方法。最好的办法是你选择的人。

There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.

variable.constructor === Array

这是在Chrome最快的方法,最有可能的所有其他浏览器。所有的数组都是对象,所以检查constructor属性是JavaScript引擎一个快速的过程。

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

如果您有查不到如果一个对象属性是一个数组的问题,必须首先检查该属性是存在的。

If you are having issues with finding out if an objects property is an array, you must first check if the property is there.

variable.prop && variable.prop.constructor === Array

其他的一些方法是:

Some other ways are:

variable instanceof Array

此方法约1/3运行速度作为第一个例子。尽管如此pretty实,看上去更清洁的,如果你所有关于pretty code和没有那么多的性能。 更新:的instanceof 这现在去2/3的速度!然而,对于那些希望它是一个一站式商店,它不与数字工作。

This method runs about a 1/3rd the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Update: instanceof This now goes 2/3rd the speed! However, for those wanting it to be a one stop shop, it does not work with numbers.

Array.isArray(variable)

这最后一个是,在我看来最丑陋的,它是一个最慢的。运行约1/5的转速作为第一个例子。 Array.prototype,实际上是一个数组。你可以阅读更多关于它在这里<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

This last one is, in my opinion the ugliest, and it is one the slowest. Running about 1/5th the speed as the first example. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

于是又更新

Object.prototype.toString.call(variable) === '[object Array]';

这家伙是最慢的尝试检查一个数组。然而,这是你要找的任何类型的一站式服务。不过,既然你正在寻找一个数组,只需使用上面的最快方法。

This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.

另外,我在jsperf.com <一跑了一些测试href=\"http://jsperf.com/instanceof-array-vs-array-isarray/33\">http://jsperf.com/instanceof-array-vs-array-isarray/33所以有一些乐趣,并检查了。

Also, I ran some test upon jsperf.com http://jsperf.com/instanceof-array-vs-array-isarray/33 so have some fun and check it out.

这篇关于你如何检查是否变量是在JavaScript中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆