[英]Basics in for loop in actionscript 3 in flex
Good Morning stackoverflow... I'm having a problem.... this is my sample code 早上好stackoverflow ...我遇到了问题....这是我的示例代码
var i:Number = new Number();
trace("showarray length" + showArray.length);
for(i=0;i<showArray.length;i++){
trace("equal daw" + showArray.getItemAt(i).id + "==" + num);
if(showArray.getItemAt(i).id == num){
showArray.removeItemAt(i);
}
}
trace('alerts');
myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop 我的问题是...只要满足,它就会停止循环,然后立即退出循环
this is a sample output given that the length of showArray is 2 and num = 0 假设showArray的长度为2并且num = 0,这是一个示例输出
showarray length2 showarray length2
equal daw0==0 等于daw0 == 0
alerts 警报
please help me 请帮我
If you want to remove items while iterating over array, iterate in reverse order. 如果要在遍历数组时删除项目,请以相反的顺序进行迭代。 This way element removal does not affect cycle condition:
这样,元素删除不会影响循环条件:
for (var i:int = showArray.length - 1; i >= 0; i--) {
if (someCondition) {
showArray.removeItemAt(i);
}
}
Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step. 另一个小好处是,它稍快一些,因为它没有在每个步骤上调用showArray.length。
An even better way might be to use the filter
method of the Array
class. 更好的方法可能是使用
Array
类的filter
方法。
array = array.filter(function (e:*, i:int, a:Array):Boolean {
return e.id != num;
});
当你的if
是满足的id == num
(这是0在第一回路所以发生),并且项被移除时,您的阵列长度减小到1,因此环将不会运行任何更多。
That's because you are removing items at the time you are iterating throught them. 那是因为您要在遍历项目时删除它们。
array = [1, 2]
^ // pointer in first iteration
eliminate 1
array = [2]
^ // the pointer remains in the same location
//ups! out of the loop. all items were visited.
You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards. 您可以在遍历数组之前对其进行复制,然后对副本进行遍历,或者标记索引以将其删除,以后再将其删除或向后迭代数组。
PS: Sorry for my poor English. PS:对不起,我英语不好。
After showArray.removeItemAt(i);
在
showArray.removeItemAt(i);
, add i--;
,加上
i--;
Because you removed the item at index i
from the array, the item that was at i + 1
got moved to i
. 由于您从数组中删除了索引
i
处的项目,因此位于i + 1
处的项目移至了i
。 By subtracting one, you ensure that the moved item doesn't get skipped. 通过减去一个,可以确保不跳过移动的项目。
alxx's answer is also a good solution. alxx的答案也是一个很好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.