Chrome re-ordering object keys if numerics, is that normal/expected

后端 未结 7 1492

I noticed that certain code that evaluates some shoe sizes for an e-commerce site and outputs them on screen is messing up the order in Chrome.

JSON given can be:

相关标签:
7条回答
  • 2020-12-03 07:13

    I found an easy work around using underscore.js

    myArray = _.sortBy(myArray, function(num){ return Math.ceil(num); });
    

    Yay! myArray is back to the correct order in all browsers.

    0 讨论(0)
  • 2020-12-03 07:15

    They're being treated as strings because they are strings. My best suggestion would be to use the same "precision" in all your keys.

    {
      "7.0": ["9149", "9139", "10455", "17208"],
      "7.5": ["9140", "9150", "10456", "17209"],
      "8.0": ["2684", "9141", "10457", "17210"],
      "8.5": ["9142", "10444", "10458", "17211"],
      "9.0": ["2685", "9143", "10459", "17212"],
      "9.5": ["10443", "9144", "10460", "17213"]
    }
    

    So, "8.0" instead of "8", etc.

    Even then, there are no guarantees, but it is more likely that they'll come out in the same order.

    For a better guarantee, perform a sort based on the keys, putting the values into an array in the sorted order.

    0 讨论(0)
  • 2020-12-03 07:17

    It would appear that Chrome is treating the integer string as if it were a numeric type when used as an index/property name.

    I think relying on the Javascript implementation to preserve the order of what, in some cases, is object properties, and in other cases (certainly with chrome) array indices, is demonstrably an unsafe approach and order of enumeration is probably not defined in the spec. I would suggest adding an additional property to the JSON that indicates a sort order:

    {
        "7":{"sortOrder":1,"data":["9149","9139","10455","17208"]},
        "7.5":{"sortOrder":2,"data":["9140","9150","10456","17209"]}
        //etc
    }
    
    0 讨论(0)
  • 2020-12-03 07:19

    When iterating over the properties of an object, the order is specified in the ECMAScript specification as being undefined and any order you may have observed in some environment should not be relied upon. If you need order, use an Array.

    0 讨论(0)
  • 2020-12-03 07:22

    It's the way v8 handles associative arrays. A known issue Issue 164 but it follows the spec so is marked 'working as intended'. There isn't a required order for looping through associative arrays.

    A simple workaround is to precede number values with letters e.g: 'size_7':['9149','9139'] etc.

    The standard will change in the next ECMAScript spec forcing [chrome] developers to change this.

    0 讨论(0)
  • 2020-12-03 07:38

    I don't think you can call this a bug. Like you say yourself, there is no garantee on how the properties of an object are sorted.

    0 讨论(0)
提交回复
热议问题