开发者

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 开发者_如何学Gobecause my keys are strings and not integers, however is there a way to specify the order it loops through them?

Thanks!!


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. :)


you could hack it by classing-out your "_propsList" object creating an array inside of the newly created PropsList class that references the properties in order. At that point, you could run a FOR loop on the array and get your properties in order.

OR, you could have a function inside that new class that would return an Array of those properties. like this:

public function getProps():Array {
    return [myPropertyOne, myPropertyTwo, myPropertyThree];
}


In general, I think this is a case where you shouldn't depend on a particular behavior from the framework/language you are using. This type of behavior is generally poorly documented and can change from version to version.

If you really need a specific retrieval order, I would create a wrapper class as jevinkones suggested above. Maybe there's even a utility class in the framework somewhere to accomplish this (Dictionary, etc.?)

HTH, Karthik


I found this link that gives some background: Subtle Change in for..in Loops for ActionScript 3

This question is actually a dup of this one.


How about using an array representation like this:

var _propsList:Array = [
    ['Type', 'product_type'],
    ['Kind', 'product_type_sub'],
    ['Stone', 'primary_stone'],
    ['Stone Color', 'primary_stone_sub'],
    ['Metal', 'metal_type'],
    ['Brand', 'product_brand']
];

for(var i in _propsList) {
    var elem = _propsList[i];
    var key = elem[0];
    var val = elem[1]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜