Object fields sequence

前端 未结 3 813
星月不相逢
星月不相逢 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
     var rtnStr = {"000":"area000","020":"area020","030":"area030",
                  "040":"area040","047":"area047","049":"area049",
                  "050":"area050","060":"area060","070":"area070",
                  "100":"area100", "900":"area900"};
    
      array_ = [];
    
      for (var key in rtnStr) {
        array_.push(key)
      }
    
      array_.sort();
    
    
      for (var key in array_) {
        document.write('rtnStr[' + key + ']= ' + rtnStr[key] + '<br />');
      }
    
    0 讨论(0)
  • 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] + '<br />');
    });
    

    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.

    0 讨论(0)
  • 2021-01-25 15:15

    JavaScript objects are unordered.

    If you want to output their properties in a sorted order then:

    1. Create an array
    2. Loop over the object, pushing the property names into the array
    3. Sort the array
    4. Loop over the array (and use the values to access the original object).
    0 讨论(0)
提交回复
热议问题