Chrome and probably Opera sort object properties automatically

前端 未结 2 714
灰色年华
灰色年华 2020-11-27 21:56

Problem is: Chrome automatically sorts properties of object.

If I have an object like:

var obj = {4: \"first\", 2: \"second\", 1: \"third\"};
         


        
相关标签:
2条回答
  • 2020-11-27 22:15

    Never rely on the order of properties. They are unordered and there is no specification that defines in which order properties should be enumerated.

    Chrome orders properties with numeric keys numerically, whereas other browsers enumerate them in insertion order. It is implementation dependent.

    0 讨论(0)
  • 2020-11-27 22:28

    You should not expect any particular order for keys in for..in loops. From the MDC docs:

    A for...in loop iterates over the properties of an object in an arbitrary order

    If you want ordering using numerical keys, use an array.

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