Order of keys returned via Object.keys from an object

后端 未结 1 620
忘了有多久
忘了有多久 2020-12-22 00:06

Object keys are not guaranteed to be ordered. Keys can be numerical or strings.

Object.keys(yourObject) returns an array of the keys on that object as strings.

相关标签:
1条回答
  • 2020-12-22 00:13

    I think the order is implementation-specific. From section 15.2.3.14 of the EcmaScript spec for Object.keys:

    If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used in step 5 of this algorithm.

    ("this algorithm" refers to the algorithm in the spec for generating the return value for Object.keys.)

    And from section 12.6.4 of the spec (on the for-in statement):

    The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

    Note also that lexicographical order is not the same as numerical order. For instance, if the keys are "1", "2", and "10", lexicographical order is "1", "10", "2". (All JS engines that I tested on return numerical order: "1", "2", "10".)

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