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
-
It depends on where this array come fromSergeS– SergeS2013年01月23日 08:05:32 +00:00Commented Jan 23, 2013 at 8:05
-
@SergeS: I do not understand you.Wolfgang Adamec– Wolfgang Adamec2013年01月23日 08:08:32 +00:00Commented Jan 23, 2013 at 8:08
3 Answers 3
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();
}
4 Comments
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.
Comments
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]
}