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

后端 未结 7 1529

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: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.

提交回复
热议问题