Elements order in a “for (… in …)” loop

后端 未结 9 697
终归单人心
终归单人心 2020-11-21 07:27

Does the \"for…in\" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn\'t do it in order?
The object

9条回答
  •  猫巷女王i
    2020-11-21 08:19

    Iteration order is also confused with respect to deleting of properties, but in this case with IE only.

    var obj = {};
    obj.a = 'a';
    obj.b = 'b';
    obj.c = 'c';
    
    // IE allows the value to be deleted...
    delete obj.b;
    
    // ...but remembers the old position if it is added back later
    obj.b = 'bb';
    for (var p in obj) {
        alert(obj[p]); // in IE, will be a, bb, then c;
                       // not a, c, then bb as for FF/Chrome/Opera/Safari
    }
    

    The desire for changing the spec to fix the iteration order seems to be quite a popular desire among developers if the discussion at http://code.google.com/p/v8/issues/detail?id=164 is any indication.

提交回复
热议问题