JavaScript:循环访问数组 [英] JavaScript: Looping over array

查看:141
本文介绍了JavaScript:循环访问数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果得出结论:循环JavaScript数组的最快方法是使用for-in循环,会不会是错误的?例如:

  for(var index in items){
...
}

请参阅 http://jsperf.com/loop-test2/2

解决方案

for-in 语句不应该用于迭代,而不是用于数组或类似数组元素。 这个语句的枚举对象的属性。

它不应该用于类似数组的对象,因为:




  • 迭代顺序不能保证,数组索引可能不会以数字顺序访问。

  • 继承的属性也被枚举。



要在数组上遍历,一个顺序循环始终是

推荐文章:



编辑:哦,我忘了提及测试是<因为表达式 new Array(10000)简单地初始化一个Array对象,其中 10000 完全偏向作为长度属性的值,数字索引属性甚至不存在,这就是为什么它看起来像成为最快的例子:

  var a = new Array(10); 
a.length; // 10
a.hasOwnProperty('0'); //假,索引甚至不存在!
a.hasOwnProperty('1'); // false
// ...

尝试这个公平测试,一个真的包含10000个元素的数组对象,您会感到惊讶。 :)

Would it be wrong to conclude that the fastest way to loop over a JavaScript array would be to use the for-in loop? E.g.:

for (var index in items) {
    ...
}

See http://jsperf.com/loop-test2/2

解决方案

The for-in statement shouldn't be used to iterate over array or array-like elements.

The purpose of this statement to enumerate object properties.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed, the array indexes may not visited in the numeric order.
  • Inherited properties are also enumerated.

To iterate over an array, a sequential loop is always recommended.

Recommended article:

Edit: Oh also, I forgot to mention that your test is completely biased, because the expression new Array(10000) simply initializes an Array object with 10000 as the value of the length property, the numeric index properties don't even exist, that's why it seems to be the fastest e.g.:

var a = new Array(10);
a.length; // 10
a.hasOwnProperty('0'); // false, the indexes don't even exist!
a.hasOwnProperty('1'); // false
//...

Try this fair test, with an array object that really contains 10000 elements and you will be surprised. :)

这篇关于JavaScript:循环访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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