AS3 - for (… in …) vs for each (… in …)

↘锁芯ラ 提交于 2019-12-20 16:50:44

问题


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);
}

回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/7137596/as3-for-in-vs-for-each-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!