简体   繁体   中英

Order of keys returned via Object.keys from an object

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM