Search code examples
apache-flexactionscript-3loopsfor-loop

AS3: Whats determines the order of: for..in


OK I am looping through the properties in an object like so:

private var _propsList:Object = {'Type':'product_type'
                        ,'Kind':'product_type_sub'
                        ,'Stone':'primary_stone'
                        ,'Stone Color':'primary_stone_sub'
                        ,'Metal':'metal_type'
                        ,'Brand':'product_brand'};

for(key in _propsList)
{
    val = _propsList[key];
    trace(key +" = "+ val);
}

I am expecting the first trace to be Type = property_type since that is the first one defined in the array, however it is coming up random everytime. I guess this is because my keys are strings and not integers, however is there a way to specify the order it loops through them?

Thanks!!


Solution

  • You can't rely on for (v in someObject) ... to return things in a predictable order, no.

    Depending on your specific situation, you could just use an array to hold the keys, and just iterate through that:

    private var keys:Array = ["Type", "Kind", "Stone", "Stone Color", "Metal", "Brand"];
    
    private function iterate():void
    {
        for each (var k:String in keys)
        {
            trace(_propsList[k]);   
        }
    }
    

    Maybe a bit obvious or non-elegant, but it'd get the job done. :)