简体   繁体   中英

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". In this method, the "widgets"-Array from above is changed. Does this array-changing in "changeWidgetArray" affect the loop iteration?

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.

Or does this depend on the JavaScript implementation? Is this defined in the ECMA-Script specification?

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.

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.

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]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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