Order of keys returned via Object.keys from an obj

2020-02-15 03:48发布

问题:

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.

On Chrome, Safari, Firefox, and in node.js if you create numerical keys on an object and return them with Object.keys(), they are all in lexicographical order. As long as the strings are representative of their literal versions (no leading 0's for example) then they are in numerical order.

What I am trying to answer is if Object.keys() guarantees the keys are returned in lexicographical order, or if this is simply an artifact of the defacto implementations in the popular browser/js environments.

回答1:

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".)