Skip to main content
Harvolev
Participating Frequently
June 24, 2009
Answered

Loop not completing

  • June 24, 2009
  • 1 reply
  • 606 views

I have a simple Loop in a function, that I'm using to remove all elements of the array:

for(var i:int = 0;  i < tempArray.length; i++)

{

     tempArray.pop();

     trace("popping: " + tempArray.length);




The probelem i'm having is that the loop does not complete. It seems to only remove one element, somtimes it will remove two. Could an event that is triggered in a separate function occur that prevents this from executing to completion?

is there another method i could use to remove all the elements?

This topic has been closed for replies.
Correct answer kglad

use:


for(var i:int = tempArray.length-1;i>=0; i--)

{

     tempArray.pop();

     trace("popping: " + tempArray.length);



1 reply

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
June 24, 2009

use:


for(var i:int = tempArray.length-1;i>=0; i--)

{

     tempArray.pop();

     trace("popping: " + tempArray.length);



Harvolev
HarvolevAuthor
Participating Frequently
June 24, 2009

Haha, awesome, i'm honestly surprised that worked. i used:

for(var i:int = tempArray.length; i>0; i--)

{

     tempArray.pop();

     trace("popping: " + tempArray.length);

}

which is essentially the same thing. How come this works for decrementing and not for incrementing?

kglad
Community Expert
Community Expert
June 24, 2009

your first code snippet will fail because you are changing the array's length during each loop iteration and the end-condition of a for-loop is checked after each loop iteration.  the intial condition is only checked at the for-loop's start.

you could also hardcode your array's length:

var L:int=tempArray.length

for(var i:int =0;i<L; i++)

{

     tempArray.pop();

     trace("popping: " + tempArray.length);

}