The problem with this code is that the thing you are checking (array.length)
is also what your are decrementing (by poping) and when combined with an
incremental counter it wont work.
ie.

Loop0 i=0 length=2

Loop1 i=1 length=1(cos weve pop'd one of the array)

Loop2 nevers happens as i<length is not true

In this particular situation actually the easiest solution is to use
Array.splice(0) which will clear the array in one command.  

But if you need to do processing on each loop then use a while loop 
var i=errors.length
while(-1<--i){
        errors.pop()
}

Rob

-----Original Message-----
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Judah
Frangipane
Sent: Sunday, November 20, 2005 11:48 AM
To: Flashcoders mailing list
Subject: [Flashcoders] Array Madness - test yourself


I just want to bring to your attention a rare array problem that eluded 
me for years. I just realized what is going on.

Whenever I tried to clear an array I would use a for loop, iterate 
through all the items and pop each one off. Every once in a while the 
arrays would still contain values and not be completely erased. Can you 
spot the error? Here is the code:

*****************************************
wrong way
*****************************************
// create an array
errors = new Array()
// add two items
errors.push("item 1")
errors.push("item 2")

// loop through each item
for (var i=0;i < errors.length; i++) {
    trace("removing item")
    errors.pop()
}
// errors.length = 1
trace("errors.length="+errors.length)


*****************************************
right way
*****************************************
// create an array
errors = new Array()
// add two items
errors.push("item 1")
errors.push("item 2")
var len = errors.length;

// loop through each item
for (var i=0;i < len; i++) {
    trace("removing item")
    errors.pop()
}
// errors.length = 0
trace("errors.length="+errors.length)


Look at the condition (i < errors.length).

If we pop an item off the end of the array then the length of the array 
is decreased and we do not iterate through all items in the array. Hope 
this helps someone.

Best Regards,
Judah



_______________________________________________
Flashcoders mailing list
[email protected]
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders



_______________________________________________
Flashcoders mailing list
[email protected]
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

Reply via email to