简体   繁体   English

JavaScript数组迭代方法

[英]JavaScript array iteration method

I have a for loop which iterates through all items: 我有一个循环遍历所有项目的循环:

for (i=0; i < this.widgets.length; i++) {
  this.changeWidgetArray(this.widgets[i]); 
}

In the for loop, for every single element, I call "changeWidgetArray". 在for循环中,对于每个单个元素,我都将其称为“ changeWidgetArray”。 In this method, the "widgets"-Array from above is changed. 在此方法中,从上方更改了“小部件”数组。 Does this array-changing in "changeWidgetArray" affect the loop iteration? 更改“ changeWidgetArray”中的数组是否会影响循环迭代?

My question is: 我的问题是:

In the moment, when the iteration begins with the first item, is the whole array with all of its elements "collected", or does JavaScript dynamically fetch one by one before the next iteration step begins. 此刻,当迭代从第一项开始时,是“收集”了其所有元素的整个数组,还是JavaScript在下一迭代步骤开始之前动态地逐个获取了数组。

Or does this depend on the JavaScript implementation? 还是这取决于JavaScript实现? Is this defined in the ECMA-Script specification? 这是在ECMA-Script规范中定义的吗?

Thanks alot in advance 在此先感谢

YES : 是的

for (i=0; i < this.widgets.length; i++) {
  this.changeWidgetArray(); 
}

NO :

for (var i=0, max=this.widgets.length; i < max; i++) {
  this.changeWidgetArray(); 
}

During the loop iteration, no variables are cached . 在循环迭代期间, 不会 缓存 任何变量。 (Unless you do that yourself in temporary variables) (除非您自己在临时变量中执行此操作)

So, this.widgets.length will be the exact length of the widgets array, each time it's evaluated, because the value of length is updated each time the array is changed. 因此, this.widgets.length将是widgets数组每次被评估时的确切长度,因为每次更改数组时都会更新length的值。

You can cache the length by assigning it to a temporary variable like this: 您可以通过将长度分配给一个临时变量来缓存长度,如下所示:

for (var i=0, l = this.widgets.length; i < l; i++) {

But that might be a bad idea, since you're changing the array in the loop, possibly making you point to invalid indexes in the array. 但这可能不是一个好主意,因为您要在循环中更改数组,这可能使您指向数组中的无效索引。

The array length is updated every time you modify the collection it contains. 每次修改数组包含的集合时,数组长度都会更新。 Any time you reference array.length, it will reflect the current size of the array. 每次引用array.length时,它将反映当前数组的大小。

For that reason, as well as many performance benefits, you should always write your code like this: 出于这个原因,以及许多性能优势,您应该始终这样编写代码:

for(var i = 0, l = array.length; i < l; i++){
  // Do stuff with array[l]
}

You can also eek a little more performance if you do it like this (assuming the direction you traverse doesn't matter): 如果这样做的话,您还可以寻求更多的性能(假设遍历的方向无关紧要):

var l = array.length;
while(l--){
  // Do stuff with array[l]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM