0

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

0

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Agree, have to iterate in reverse: answered very similar here: stackoverflow.com/questions/4946007/…
3

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

Comments

1

When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.

Comments

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.

1 Comment

Copying the array is unnecessary and slow, when you can just iterate through it backwards and have no problem
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.