Iterating over an array of objects in Javascript - why can't I obtain current object inside for increment block?
Let's say I have an array
var array = [
{name: "woo"},
{name: "yay"},
{name: "hoopla"}开发者_如何学C
]
Why does this work
for (var i=0; i<array.length; i++) {
var item=array[i];
alert(item.name) // woo, yay, hoopla
}
But this doesn't?
var item;
for (var i=0; i<array.length; item=array[i++]) {
alert(item.name) // undefined
}
Here's a jsPerf test case comparing the speed of different answers: http://jsperf.com/different-ways-to-iterate-over-an-array-of-objects/2
In the first iteration of the loop, item=array[i++]
has not been executed yet, so item
still has its initial value. The third part of a for
statement is executed in between iterations, but not when the loops starts.
This should work
var item;
for (var i=0; item=array[i], i<array.length; i++) {
alert(item.name) // undefined
}
It because the first time through the loop, the variable item
doesn't get assigned
A for
statement has 3 parts, the counter (var i= 0;), the limit (i<array.length;) and the incrementor(i++;)
Think of those bits as 3 different lines of code. However instead of the three lines being executed in sequence, this is what the sequence looks like
- The 'counter' is executed and sets the variable
- The 'limit' is checked and if the boolean is
true
the code in the braces is executed - After the code in the braces is executed, the 'incrementor' is executed
- cycle repeats from the second step till the limit returns
false
The last bit the incrementor doesn't get executed until AFTER the code in the braces of the for
loop has been executed, so essentially, at that point in time, item had not been assigned.
Because in the first iteration item
is not defined yet, it will work if you change your code to:
for ( item=array[i=0]; i<array.length; item=array[++i] ) {
alert(item.name)
}
Another way of enumerating an array of objects in JavaScript:
for(var item in array)
alert(array[item])
精彩评论