简体   繁体   中英

Basics in for loop in actionscript 3 in flex

Good Morning stackoverflow... I'm having a problem.... this is my sample code

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 length2

equal 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.

An even better way might be to use the filter method of the Array class.

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.

After showArray.removeItemAt(i); , add i--;

Because you removed the item at index i from the array, the item that was at i + 1 got moved to i . By subtracting one, you ensure that the moved item doesn't get skipped.

alxx's answer is also a good solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM