本文介绍了从对象通过Object.keys返回的键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能保证对象键是有序的.键可以是数字或字符串.

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

Object.keys(yourObject)以字符串的形式返回该对象上的键的数组.

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

在Chrome,Safari,Firefox和node.js中,如果您在对象上创建数字键并使用Object.keys()返回它们,则它们均按字典顺序排列.只要字符串代表其文字版本(例如,无前导0),那么它们就按数字顺序.

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.

我要回答的是如果Object.keys()保证键是按字典顺序返回的,或者这仅仅是流行的浏览器/js环境中实际实现的产物

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.

推荐答案

我认为该命令是特定于实现的.从EcmaScript规范的15.2.3.14节中获取的Object.keys:

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

(此算法"是指规范中用于生成Object.keys的返回值的算法.)

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

根据规范的12.6.4节(在for-in语句上):

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

还请注意,字典顺序与数字顺序不同.例如,如果键是"1","2"和"10",则字典顺序是"1","10","2". (我测试过的所有JS引擎都返回数字顺序:"1","2","10".)

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

这篇关于从对象通过Object.keys返回的键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:06