I'm a bit stumped by the exact order of execution of a particular for loop I'm playing with, in Codepen. Check out these two loops, which both do the same thing:
var a = ['orange','apple'];
for (var i=0; i<2;i++) {
alert(a[i]);
}
for (var j=0, fruit; fruit = a[j++];) {
alert(fruit);
}
The first loop is the standard, vanilla way of writing a for loop. As expected, it alerts "orange", then "apple".
It works, but I don't quite understand why. My understanding of for loops, which is obviously incorrect in some way (more than one way?) is that:
* The for loop evaluates the truthiness of the second expression before it runs the first time. So it seems that when the for loop is evaluating the truthiness of the second expression, it should increment j before setting the value of fruit. So the first time through the loop, fruit should equal "apple".
* And the loop should only run once, because after the first time through, when it's evaluating the second expression again to see if it's still true, it should once again increment j before it returns a value to fruit, and since there is no value at index position 2, it should return a falsy result, and exit the loop.
I don't understand what actually IS happening. Does the for loop run once before the second expression is evaluated? But that seems impossible, because if that happened, the alert would alert nothing the first time through, since fruit wouldn't yet have a value.
Also, the author of the MDN article seemed to like the second way of writing the loop - is there a reason that way is better? It uses fewer characters, which is good, I guess. Does skipping the third expression in the for loop save significant time? Or is it just a "it's cool because it's clever" sort of thing?
解决方案
for (var j=0, fruit; fruit = a[j++];) {
alert(fruit);
}
In pseudocode is equal to:
initialize j = 0 and fruit = undefined
assign fruit = a[j] (j = 0, fruit = 'orange')
j = j + 1 (j = 1)
check fruit for being truthy (true)
alert(fruit) ('orange')
assign fruit = a[j] (j = 1, fruit = 'apple')
j = j + 1 (j = 2)
check fruit for being truthy (true)
alert(fruit) ('apple')
assign fruit = a[j] (j = 2, fruit = undefined)
j = j + 1 (j = 3)
check fruit for being truthy (false)
exit loop
Important note:
The postfix unary ++ operator works as:
We return the current value of the variable
We increment the value of the variable
Does skipping the third expression in the for loop save significant time?
It does not save anything at all
Also, the author of the MDN article seemed to like the second way of writing the loop - is there a reason that way is better?
It's not better in any way. Author just thinks it's cool and author likes to be cool (while they are not).