Deleted array value still showing up on foreach loop in AS3 (bug in flash?)

Posted by nexus on Stack Overflow See other posts from Stack Overflow or by nexus
Published on 2010-04-07T20:10:17Z Indexed on 2010/04/07 20:13 UTC
Read the original article Hit count: 131

Filed under:
|
|
|

It took me many hours to narrow down a problem in some code to this reproducible error, which seems to me like a bug in AVM2. Can anyone shed light on why this is occurring or how to fix it?

When the value at index 1 is deleted and a value is subsequently set at index 0, the non-existent (undefined) value at index 1 will now show up in a foreach loop. I have only been able to produce this outcome with index 1 and 0 (not any other n and n-1).

Run this code:

package 
{
import flash.display.Sprite;
public class Main extends Sprite 
{
    public function Main():void 
    {
        var bar : Array = new Array(6);
        out(bar);

        //proper behavior
        trace("bar[1] = 1", bar[1] = 1);
        out(bar);

        //proper behavior
        trace("delete bar[1]", delete bar[1]);
        out(bar);

        //proper behavior
        trace("bar[4] = 4", bar[4] = 4);
        out(bar);

        //for each loop will now iterate over the undefined position at index 1
        trace("bar[0] = 0", bar[0] = 0);
        out(bar);

        trace("bar[3] = 3", bar[3] = 3);
        out(bar);
    }

    private function out(bar:Array):void
    {
        trace(bar);
        for each(var i : * in bar)
        {
            trace(i);
        }
    }
}

}

It will give this output:

,,,,,
bar[1] = 1 1
,1,,,,
1
delete bar[1] true
,,,,,
bar[4] = 4 4
,,,,4,
4
bar[0] = 0 0
0,,,,4,
0
undefined
4
bar[3] = 3 3
0,,,3,4,
0
undefined
4
3

© Stack Overflow or respective owner

Related posts about as3

Related posts about actionscript-3