如何检查一个变量是否是JavaScript中的数组?(复制)

时间:2023-01-11 07:29:16

This question already has an answer here:

这个问题已经有了答案:

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

我想要检查一个变量是数组还是JavaScript中的一个值。

I have found a possible solution...

我找到了一个可能的解决办法……

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

Is this the best way this can be done?

这是最好的方法吗?

24 个解决方案

#1


1227  

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

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.

这是Chrome上最快的方法,而且很可能是所有其他浏览器。所有数组都是对象,因此检查构造函数属性是JavaScript引擎的一个快速过程。

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

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!

这个方法的速度是第一个例子的1/3。仍然是相当可靠的,看起来更干净,如果你是关于漂亮的代码,而不是关于性能。注意,对数字的检查不能作为变量instanceof数字工作,总是返回false。更新:instanceof现在的速度是2/3 !

Array.isArray(variable)

This last one is, in my opinion the ugliest, and it is one of the slowest. Running about 1/5 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

最后一个是,在我看来最丑的,也是最慢的。以1/5的速度作为第一个例子。数组中。原型,实际上是一个数组。你可以在这里读到更多关于它的信息。

So yet another update

所以另一个更新

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.

这个家伙是检查数组的最慢的。然而,这是一个一站式商店,你想要的任何类型。但是,既然您正在寻找一个数组,那么就使用上面最快的方法。

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

此外,我还运行了一些测试:http://jsperf.com/instanceof-array-vs-array-isarray/33,所以有一些乐趣,并进行检查。

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

注意:@EscapeNetscape创建了另一个测试,因为jsperf.com已经关闭。http://jsben。ch/#/QgYAV我想确保当jsperf上线时,原始的链接可以保留。

#2


966  

You could also use:

你也可以使用:

if (value instanceof Array) {
  alert('value is Array!');
} else {
  alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

在我看来,这是一个相当优雅的解决方案,但对每个人来说都是如此。

Edit:

编辑:

As of ES5 there is now also:

到ES5的时候,现在也有:

Array.isArray(value);

But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).

但是这将会在旧的浏览器上出现,除非你使用的是poly(基本上……)IE8或类似)。

#3


72  

I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.

我注意到有人提到了jQuery,但我不知道有一个isArray()函数。结果是在1.3版本中添加的。

jQuery implements it as Peter suggests:

jQuery实现了它,正如Peter所建议的:

isArray: function( obj ) {
    return toString.call(obj) === "[object Array]";
},

Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.

我已经对jQuery有了很大的信心(特别是对跨浏览器兼容性的技术),我将升级到1.3版本,并使用它们的功能(提供升级不会带来太多问题),或者直接在我的代码中使用这个建议的方法。

Many thanks for the suggestions.

非常感谢您的建议。

#4


71  

There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:

有各种各样的解决方案。这个页面提供了一个很好的概述。一个可能的解决方案是:

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

#5


51  

In modern browsers (and some legacy browsers), you can do

在现代浏览器(以及一些遗留浏览器)中,您可以这样做。

Array.isArray(obj)

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

(支持Chrome 5, Firefox 4.0, ie9, Opera 10.5和Safari 5)

If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following

如果您需要支持旧版本的IE,您可以使用es5-shim到polyfill Array.isArray;或添加以下

# 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

Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:

注意:可以用来访问函数参数的参数关键字不是数组,尽管它(通常)的行为类似于:

var func = function() {
  console.log(arguments)        // [1, 2, 3]
  console.log(arguments.length) // 3
  console.log(Array.isArray(arguments)) // false !!!
  console.log(arguments.slice)  // undefined (Array.prototype methods not available)
  console.log([3,4,5].slice)    // function slice() { [native code] } 
}
func(1, 2, 3)

#6


49  

This is an old question but having the same problem i found a very elegant solution that i want to share.

这是一个老问题,但有同样的问题,我找到了一个非常优雅的解决方案,我想分享。

Adding a prototype to Array makes it very simple

将原型添加到数组中使其变得非常简单。

Array.prototype.isArray = true;

Now once if you have an object you want to test to see if its an array all you need is to check for the new property

现在,如果你有一个对象你想测试它是否一个数组你所需要的是检查新属性。

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray is only available if its an array

isArray只有在数组中才可用。

#7


45  

Via Crockford:

通过Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

Crockford提到的主要缺点是不能正确地确定在不同的上下文中创建的数组,例如,window。如果这个页面不够,那么这个页面的版本就会更加复杂。

#8


26  

I personally like Peter's suggestion: https://*.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())

我个人喜欢Peter的建议:https://*.com/a/767499/414784(用于ECMAScript 3)。对于ECMAScript 5,使用Array.isArray()

Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:

但是,post上的注释表明,如果toString()发生了变化,那么检查数组的方式将会失败。如果您确实想要具体并确保toString()没有被更改,并且对象类属性([object Array]是对象的class属性是数组)没有问题,那么我建议您这样做:

//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')
    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    else
    {
        // may want to change return value to something more desirable
        return -1; 
    }
}

Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.

请注意,在JavaScript中,最终指南第6版,7.10,它说Array.isArray()是使用Object.prototype.toString.call()在ECMAScript 5中实现的。还要注意的是,如果您要担心toString()的实现发生变化,那么您也应该担心其他在方法中构建的方法也会发生变化。为什么使用push()?有人可以改变它!这种做法是愚蠢的。上面的检查是为那些担心toString()变化的人提供的解决方案,但是我认为检查是不必要的。

#9


19  

When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.

当我发布这个问题时,我使用的JQuery版本没有包含isArray函数。如果它有的话,我可能会用它来相信实现是最好的浏览器独立的方式来执行这个特定类型的检查。

Since JQuery now does offer this function, I would always use it...

既然JQuery现在提供了这个功能,我将一直使用它……

$.isArray(obj);

(as of version 1.6.2) It is still implemented using comparisons on strings in the form

(在版本1.6.2中),它仍然使用表单中字符串的比较来实现。

toString.call(obj) === "[object Array]"

#10


16  

Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).

我想为那些已经使用下划线的人添加另一个选项。js库的脚本。下划线。js有一个isArray()函数(参见http://underscorejs.org/#isArray)。

_.isArray(object) 

Returns true if object is an Array.

返回true,如果对象是一个数组。

#11


13  

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function

如果您只处理EcmaScript 5和以上,那么您可以使用内置数组。isArray函数

e.g.,

例如,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false

#12


10  

If you are using Angular, you can use the angular.isArray() function

如果使用角度,可以使用angular.isArray()函数。

var myArray = [];
angular.isArray(myArray); // returns true

var myObj = {};
angular.isArray(myObj); //returns false

http://docs.angularjs.org/api/ng/function/angular.isArray

http://docs.angularjs.org/api/ng/function/angular.isArray

#13


9  

In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:

在Crockford的JavaScript中,好的部分,有一个函数来检查给定的参数是否是一个数组:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

He explains:

他解释说:

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

首先,我们问价值是否真实。我们这样做是为了拒绝null和其他假值。其次,我们询问类型值是否为“对象”。这对于对象、数组和(奇怪的)null都是正确的。第三,我们问值是否有一个长度的属性,它是一个数字。对于数组来说,这总是正确的,但通常不是针对对象的。第四,我们询问该值是否包含splice方法。这对于所有数组都是正确的。最后,我们询问长度属性是否可枚举(是否由for循环产生长度)。这对所有数组都是错误的。这是我发现的最可靠的arrayness测试。真不幸,这事太复杂了。

#14


5  

I was using this line of code:

我用了这行代码:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}

#15


3  

code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js

从https://github.com/miksago/Evan.js/blob/master/src/evan.js代码称为

  var isArray = Array.isArray || function(obj) {
    return !!(obj && obj.concat && obj.unshift && !obj.callee);};

#16


3  

The universal solution is below:

通用解决方案如下:

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

Starting from ECMAScript 5, a formal solution is :

从ECMAScript 5开始,正式的解决方案是:

Array.isArray(arr)

Also, for old JavaScript libs, you can find below solution although it's not accurate enough:

另外,对于老的JavaScript libs,您可以找到下面的解决方案,尽管它不够精确:

var is_array = function (value) {
    return value &&
    typeof value === 'object' &&
    typeof value.length === 'number' &&
    typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript

解决方案来自http://www.pixelstech.net/topic/85-howto -check- to- to-check- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#17


2  

For those who code-golf, an unreliable test with fewest characters:

对于那些打高尔夫球的人来说,这是一个不可靠的测试,他们的角色最少:

function isArray(a) {
  return a.map;
}

This is commonly used when traversing/flattening a hierarchy:

这通常用于遍历/压平一个层次结构:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

#18


2  

From w3schools:

从w3schools:

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

#19


1  

I liked the Brian answer:

我喜欢布莱恩的回答:

function is_array(o){
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    } else{
        // may want to change return value to something more desirable
        return -1; 
    }
}

but you could just do like this:

但是你可以这样做:

return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);

#20


1  

I have created this little bit of code, which can return true types.

我已经创建了这一小段代码,它可以返回真正的类型。

I am not sure about performance yet, but it's an attempt to properly identify the typeof.

我对性能还不太确定,但它是一种试图正确识别类型的尝试。

https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/

https://github.com/valtido/well -typeof也在这里写了一些关于它的信息:http://www.jqui.net/jquery/jquery/typeof -javascript- typeof/。

it works, similar to the current typeof.

它的工作原理类似于当前的typeof。

var user = [1,2,3]
typeOf(user); //[object Array]

It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.

它认为它可能需要一些微调,并且考虑到一些事情,我没有遇到或测试它。因此,我们欢迎进一步的改进,无论它的性能是明智的,还是错误地重新移植了typeOf。

#21


1  

I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring

我认为使用myObj。构造函数对象和myArray = =。构造函数==数组是最好的方法。它比使用toString()快20倍。如果您将对象扩展到自己的构造函数,并希望这些创建被视为“对象”,而不是这样,那么它的速度就会更快。typeof和构造函数方法一样快,但是typeof[]=='对象'返回true,这通常是不可取的。http://jsperf.com/constructor-vs-tostring

one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}

需要注意的一点是null。构造函数会抛出一个错误,因此如果您可能要检查空值,那么您必须首先执行if(testThing!==null){}

#22


-3  

function isArray(x){
    return ((x != null) && (typeof x.push != "undefined"));
}

#23


-3  

Since the .length property is special for arrays in javascript you can simply say

因为.length属性对于javascript数组来说是特殊的,您可以简单地说。

obj.length === +obj.length // true if obj is an array

Underscorejs and several other libraries use this short and simple trick.

Underscorejs和其他几个库使用这个简单的技巧。

#24


-13  

Something I just came up with:

我刚想到的一件事:

if (item.length) //This is an array else //not an array

如果(item.length) //这是一个数组else //不是数组。

#1


1227  

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

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.

这是Chrome上最快的方法,而且很可能是所有其他浏览器。所有数组都是对象,因此检查构造函数属性是JavaScript引擎的一个快速过程。

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

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!

这个方法的速度是第一个例子的1/3。仍然是相当可靠的,看起来更干净,如果你是关于漂亮的代码,而不是关于性能。注意,对数字的检查不能作为变量instanceof数字工作,总是返回false。更新:instanceof现在的速度是2/3 !

Array.isArray(variable)

This last one is, in my opinion the ugliest, and it is one of the slowest. Running about 1/5 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

最后一个是,在我看来最丑的,也是最慢的。以1/5的速度作为第一个例子。数组中。原型,实际上是一个数组。你可以在这里读到更多关于它的信息。

So yet another update

所以另一个更新

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.

这个家伙是检查数组的最慢的。然而,这是一个一站式商店,你想要的任何类型。但是,既然您正在寻找一个数组,那么就使用上面最快的方法。

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

此外,我还运行了一些测试:http://jsperf.com/instanceof-array-vs-array-isarray/33,所以有一些乐趣,并进行检查。

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

注意:@EscapeNetscape创建了另一个测试,因为jsperf.com已经关闭。http://jsben。ch/#/QgYAV我想确保当jsperf上线时,原始的链接可以保留。

#2


966  

You could also use:

你也可以使用:

if (value instanceof Array) {
  alert('value is Array!');
} else {
  alert('Not an array');
}

This seems to me a pretty elegant solution, but to each his own.

在我看来,这是一个相当优雅的解决方案,但对每个人来说都是如此。

Edit:

编辑:

As of ES5 there is now also:

到ES5的时候,现在也有:

Array.isArray(value);

But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).

但是这将会在旧的浏览器上出现,除非你使用的是poly(基本上……)IE8或类似)。

#3


72  

I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.

我注意到有人提到了jQuery,但我不知道有一个isArray()函数。结果是在1.3版本中添加的。

jQuery implements it as Peter suggests:

jQuery实现了它,正如Peter所建议的:

isArray: function( obj ) {
    return toString.call(obj) === "[object Array]";
},

Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.

我已经对jQuery有了很大的信心(特别是对跨浏览器兼容性的技术),我将升级到1.3版本,并使用它们的功能(提供升级不会带来太多问题),或者直接在我的代码中使用这个建议的方法。

Many thanks for the suggestions.

非常感谢您的建议。

#4


71  

There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:

有各种各样的解决方案。这个页面提供了一个很好的概述。一个可能的解决方案是:

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

#5


51  

In modern browsers (and some legacy browsers), you can do

在现代浏览器(以及一些遗留浏览器)中,您可以这样做。

Array.isArray(obj)

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

(支持Chrome 5, Firefox 4.0, ie9, Opera 10.5和Safari 5)

If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following

如果您需要支持旧版本的IE,您可以使用es5-shim到polyfill Array.isArray;或添加以下

# 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

Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:

注意:可以用来访问函数参数的参数关键字不是数组,尽管它(通常)的行为类似于:

var func = function() {
  console.log(arguments)        // [1, 2, 3]
  console.log(arguments.length) // 3
  console.log(Array.isArray(arguments)) // false !!!
  console.log(arguments.slice)  // undefined (Array.prototype methods not available)
  console.log([3,4,5].slice)    // function slice() { [native code] } 
}
func(1, 2, 3)

#6


49  

This is an old question but having the same problem i found a very elegant solution that i want to share.

这是一个老问题,但有同样的问题,我找到了一个非常优雅的解决方案,我想分享。

Adding a prototype to Array makes it very simple

将原型添加到数组中使其变得非常简单。

Array.prototype.isArray = true;

Now once if you have an object you want to test to see if its an array all you need is to check for the new property

现在,如果你有一个对象你想测试它是否一个数组你所需要的是检查新属性。

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray is only available if its an array

isArray只有在数组中才可用。

#7


45  

Via Crockford:

通过Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

Crockford提到的主要缺点是不能正确地确定在不同的上下文中创建的数组,例如,window。如果这个页面不够,那么这个页面的版本就会更加复杂。

#8


26  

I personally like Peter's suggestion: https://*.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())

我个人喜欢Peter的建议:https://*.com/a/767499/414784(用于ECMAScript 3)。对于ECMAScript 5,使用Array.isArray()

Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:

但是,post上的注释表明,如果toString()发生了变化,那么检查数组的方式将会失败。如果您确实想要具体并确保toString()没有被更改,并且对象类属性([object Array]是对象的class属性是数组)没有问题,那么我建议您这样做:

//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')
    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    else
    {
        // may want to change return value to something more desirable
        return -1; 
    }
}

Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.

请注意,在JavaScript中,最终指南第6版,7.10,它说Array.isArray()是使用Object.prototype.toString.call()在ECMAScript 5中实现的。还要注意的是,如果您要担心toString()的实现发生变化,那么您也应该担心其他在方法中构建的方法也会发生变化。为什么使用push()?有人可以改变它!这种做法是愚蠢的。上面的检查是为那些担心toString()变化的人提供的解决方案,但是我认为检查是不必要的。

#9


19  

When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.

当我发布这个问题时,我使用的JQuery版本没有包含isArray函数。如果它有的话,我可能会用它来相信实现是最好的浏览器独立的方式来执行这个特定类型的检查。

Since JQuery now does offer this function, I would always use it...

既然JQuery现在提供了这个功能,我将一直使用它……

$.isArray(obj);

(as of version 1.6.2) It is still implemented using comparisons on strings in the form

(在版本1.6.2中),它仍然使用表单中字符串的比较来实现。

toString.call(obj) === "[object Array]"

#10


16  

Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).

我想为那些已经使用下划线的人添加另一个选项。js库的脚本。下划线。js有一个isArray()函数(参见http://underscorejs.org/#isArray)。

_.isArray(object) 

Returns true if object is an Array.

返回true,如果对象是一个数组。

#11


13  

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function

如果您只处理EcmaScript 5和以上,那么您可以使用内置数组。isArray函数

e.g.,

例如,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false

#12


10  

If you are using Angular, you can use the angular.isArray() function

如果使用角度,可以使用angular.isArray()函数。

var myArray = [];
angular.isArray(myArray); // returns true

var myObj = {};
angular.isArray(myObj); //returns false

http://docs.angularjs.org/api/ng/function/angular.isArray

http://docs.angularjs.org/api/ng/function/angular.isArray

#13


9  

In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:

在Crockford的JavaScript中,好的部分,有一个函数来检查给定的参数是否是一个数组:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

He explains:

他解释说:

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

首先,我们问价值是否真实。我们这样做是为了拒绝null和其他假值。其次,我们询问类型值是否为“对象”。这对于对象、数组和(奇怪的)null都是正确的。第三,我们问值是否有一个长度的属性,它是一个数字。对于数组来说,这总是正确的,但通常不是针对对象的。第四,我们询问该值是否包含splice方法。这对于所有数组都是正确的。最后,我们询问长度属性是否可枚举(是否由for循环产生长度)。这对所有数组都是错误的。这是我发现的最可靠的arrayness测试。真不幸,这事太复杂了。

#14


5  

I was using this line of code:

我用了这行代码:

if (variable.push) {
   // variable is array, since AMAIK only arrays have push() method.
}

#15


3  

code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js

从https://github.com/miksago/Evan.js/blob/master/src/evan.js代码称为

  var isArray = Array.isArray || function(obj) {
    return !!(obj && obj.concat && obj.unshift && !obj.callee);};

#16


3  

The universal solution is below:

通用解决方案如下:

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

Starting from ECMAScript 5, a formal solution is :

从ECMAScript 5开始,正式的解决方案是:

Array.isArray(arr)

Also, for old JavaScript libs, you can find below solution although it's not accurate enough:

另外,对于老的JavaScript libs,您可以找到下面的解决方案,尽管它不够精确:

var is_array = function (value) {
    return value &&
    typeof value === 'object' &&
    typeof value.length === 'number' &&
    typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript

解决方案来自http://www.pixelstech.net/topic/85-howto -check- to- to-check- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#17


2  

For those who code-golf, an unreliable test with fewest characters:

对于那些打高尔夫球的人来说,这是一个不可靠的测试,他们的角色最少:

function isArray(a) {
  return a.map;
}

This is commonly used when traversing/flattening a hierarchy:

这通常用于遍历/压平一个层次结构:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

#18


2  

From w3schools:

从w3schools:

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

#19


1  

I liked the Brian answer:

我喜欢布莱恩的回答:

function is_array(o){
    // make sure an array has a class attribute of [object Array]
    var check_class = Object.prototype.toString.call([]);
    if(check_class === '[object Array]')    {
        // test passed, now check
        return Object.prototype.toString.call(o) === '[object Array]';
    } else{
        // may want to change return value to something more desirable
        return -1; 
    }
}

but you could just do like this:

但是你可以这样做:

return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);

#20


1  

I have created this little bit of code, which can return true types.

我已经创建了这一小段代码,它可以返回真正的类型。

I am not sure about performance yet, but it's an attempt to properly identify the typeof.

我对性能还不太确定,但它是一种试图正确识别类型的尝试。

https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/

https://github.com/valtido/well -typeof也在这里写了一些关于它的信息:http://www.jqui.net/jquery/jquery/typeof -javascript- typeof/。

it works, similar to the current typeof.

它的工作原理类似于当前的typeof。

var user = [1,2,3]
typeOf(user); //[object Array]

It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.

它认为它可能需要一些微调,并且考虑到一些事情,我没有遇到或测试它。因此,我们欢迎进一步的改进,无论它的性能是明智的,还是错误地重新移植了typeOf。

#21


1  

I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring

我认为使用myObj。构造函数对象和myArray = =。构造函数==数组是最好的方法。它比使用toString()快20倍。如果您将对象扩展到自己的构造函数,并希望这些创建被视为“对象”,而不是这样,那么它的速度就会更快。typeof和构造函数方法一样快,但是typeof[]=='对象'返回true,这通常是不可取的。http://jsperf.com/constructor-vs-tostring

one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}

需要注意的一点是null。构造函数会抛出一个错误,因此如果您可能要检查空值,那么您必须首先执行if(testThing!==null){}

#22


-3  

function isArray(x){
    return ((x != null) && (typeof x.push != "undefined"));
}

#23


-3  

Since the .length property is special for arrays in javascript you can simply say

因为.length属性对于javascript数组来说是特殊的,您可以简单地说。

obj.length === +obj.length // true if obj is an array

Underscorejs and several other libraries use this short and simple trick.

Underscorejs和其他几个库使用这个简单的技巧。

#24


-13  

Something I just came up with:

我刚想到的一件事:

if (item.length) //This is an array else //not an array

如果(item.length) //这是一个数组else //不是数组。