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

后端 未结 9 672
终归单人心
终归单人心 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条回答
  •  灰色年华
    2020-11-21 08:12

    Bumping this a year later...

    It is 2012 and the major browsers still differ:

    function lineate(obj){
        var arr = [], i;
        for (i in obj) arr.push([i,obj[i]].join(':'));
        console.log(arr);
    }
    var obj = { a:1, b:2, c:3, "123":'xyz' };
    /* log1 */  lineate(obj);
    obj.a = 4;
    /* log2 */  lineate(obj);
    delete obj.a;
    obj.a = 4;
    /* log3 */  lineate(obj);
    

    gist or test in current browser

    Safari 5, Firefox 14

    ["a:1", "b:2", "c:3", "123:xyz"]
    ["a:4", "b:2", "c:3", "123:xyz"]
    ["b:2", "c:3", "123:xyz", "a:4"]
    

    Chrome 21, Opera 12, Node 0.6, Firefox 27

    ["123:xyz", "a:1", "b:2", "c:3"]
    ["123:xyz", "a:4", "b:2", "c:3"]
    ["123:xyz", "b:2", "c:3", "a:4"]
    

    IE9

    [123:xyz,a:1,b:2,c:3] 
    [123:xyz,a:4,b:2,c:3] 
    [123:xyz,a:4,b:2,c:3] 
    

提交回复
热议问题