Object fields sequence

前端 未结 3 814
星月不相逢
星月不相逢 2021-01-25 14:29

I have a JavaScript object written in javascript code as below:

var rtnStr = {\"000\":\"area000\",\"020\":\"area020\",\"030\":\"area030\",
              \"040\":         


        
3条回答
  •  遥遥无期
    2021-01-25 15:10

    As mentioned by @Quentin, the order of the properties in JavaScript objects is undefined. The spec doesn't even mention if the properties will be returned in the same order by different for..ins.

    What you can do is get the keys in an array and sort them:

    var rtnStr = {"000":"area000","020":"area020","030":"area030",
                  "040":"area040","047":"area047","049":"area049",
                  "050":"area050","060":"area060","070":"area070",
                  "100":"area100", "900":"area900"};
    
    var keys = Object.keys(rtnStr).sort().forEach(function(key){
      document.write('rtnStr[' + key + ']= ' + rtnStr[key] + '
    '); });

    MDN has a page for Object.keys where you can find the browsers it works on and a polyfill for those it doesn't.

    One thing to note is that your initial version of the code iterates over inherited properties as well. That is generally considered to be unsafe and Object.keys doesn't exhibit that behavior.

提交回复
热议问题