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

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

    As stated by other answers, no, the order is not guaranteed.

    If you want to iterate in order, you can do something like:

    let keys = Object.keys(myObject);
    for (let key of keys.sort()) {
      let value = myObject[key];
      
      // Do what you want with key and value 
    }
    

    Note that performance-wise, this is not optimal, but that's the price when you want a nice alphabetical display.

提交回复
热议问题