The following code does the exact same thing. Is there a difference between for each
and for (... in ...)
?
var bar:Array = new Array(1,2,3);
for (var foo in bar){
trace(foo);
}
for each (var foo2 in bar){
trace(foo2);
}
The following code does the exact same thing. Is there a difference between for each
and for (... in ...)
?
var bar:Array = new Array(1,2,3);
for (var foo in bar){
trace(foo);
}
for each (var foo2 in bar){
trace(foo2);
}
No, they do not do the exact same thing.
The output of your for..in loop is
0
1
2
While the output of your for each..in loop is
1
2
3
A for..in loop iterates through the keys/indices of an array or property names of an object. A for each..in loop iterates through the values. You get the above results because your bar
array is structured like this:
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
Some of the confusion here is that you are using numbers in your array. Let's switch to strings and see what happens.
var bar:Array = new Array("x", "y", "z");
for (var foo in bar){
trace(foo);
}
for each (var foo2 in bar){
trace(foo2);
}
Now your output is:
0
1
2
x
y
z
As you can see, for-in loops over indexes (or keys), and for-each-in loops over values.