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

后端 未结 9 674
终归单人心
终归单人心 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:01

    This does not answer the question per se, but offers a solution to the basic problem.

    Assuming that you cannot rely on order to preserved, why not use an array of objects with key and value as properties?

    var myArray = [
        {
            'key'   : 'key1'
            'value' : 0
        },
        {
            'key'   : 'key2',
            'value' : 1
        } // ...
    ];
    

    Now, it is up to you to ensure that the keys are unique (assuming that this is also important to you. As well, direct addressing changes, and for (...in...) now returns indexes as 'keys'.

    > console.log(myArray[0].key);
    key1
    
    > for (let index in myArray) {console.log(myArray[index].value);}
    0
    1
    
    See the Pen for (...in...) addressing in order by JDQ (@JDQ) on CodePen.

提交回复
热议问题