开发者

How to guarantee the ordering of a for each loop on an object in Actionscript

Suppose I have a function that I want to use to display an object's properties, in sorted order:

function showObject(obj:Object) {
    for ( var key in obj ) {
        trace("key: " + obj[key]);
    }
}

I understand that this is not guaranteed to be in any particular order; What's the best wa开发者_如何学Goy to do this, but guarantee sorted order?


You can't. It's a hashing algorithm, and for...in specifically is used to enumerate dynamic (eg hashed) properties. If you need it to return an ordered list, you should use an Array or create an ordered Hash class that you can iterate through sequentially. Just understand that you won't be able to use a for...in loop to do it. You have to build the iterator to handle that logic itself and simply call .next() on it to have it return the next item in sequence.


Does this work for you?

function showObject(obj:Object) {
    var keys:Array = new Array();
    var key;
    for ( key in obj ) {
        keys.push(key);
    }
    keys.sort();
    for ( key in obj ) {
        trace(key + ": " + obj[key]);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜