小心for loop陷阱 for loop pitfall - 适用于Java, Flex及其它语言

SNOW E 2 LOGO _áRAD_E8 下列代码试图从ArrayCollection里面删除所有元素:

for(var i:int = 0; i < ac.length; i++) {
  ac.removeItemAt(i);
}

上述代码运行后, ArrayCollection的length并不为0. 其原因不外乎for loop的body改变了ArrayCollection, 亦即for loop的body影响着for loop的condition. 这样的状况要格外注意. 就这道题来说的正确做法(因状况不同而千差万别)是:

while(ac.length > 0) {
  ac.removeItemAt(0); // reduces ac.length by 1.
}

在ArrayCollection里, 你可以轻松的使用removeAll()以清空所有元素. 实际的编程中for loop往往比较复杂, 如果for loop body里面有任何代码直接或间接改变了任何参与for loop condition的变量, 这些代码应当被清晰地注释出来.

Comments

另一個Flex常見的例子

使用objectContainer.numChildren做為迴圈索引
在移除時,ChildIndex會自動遞補,造成迴圈錯誤

--GD @ Water & Bread--
Blog http://waterxbread.blogspot.com/

补充个删除个别特定元素的例子

len = ac.length;
for(var i:int = 0; i < len; i++){
if(ac.getItemAt(i) == null || ac.getItemAt(i) == ""){
ac.removeItemAt(i);
len--;
i--;
}
}
应该没错吧.... =|

Yup, it's right.

Yup, it's right. Alternatively,

for(var i:int = 0; i < ac.length; ) {
if(ac.getItemAt(i) == null || ac.getItemAt(i) == ""){
ac.removeItemAt(i);
// continue from the current position
}else{
i++; // continue from the next position
}
}