【发布时间】:2015-07-16 13:25:25
【问题描述】:
ES6 是否为对象属性引入了明确定义的枚举顺序?
var o = {
'1': 1,
'a': 2,
'b': 3
}
Object.keys(o); // ["1", "a", "b"] - is this ordering guaranteed by ES6?
for(let k in o) {
console.log(k);
} // 1 2 3 - is this ordering guaranteed by ES6?
【问题讨论】:
-
顺便说一句,对于
Object.getOwnPropertyNames、Object.getOwnPropertySymbols和Reflect.ownKeys,顺序是定义的。 -
实际上 - 答案又是 - 不再是最新的 :) ES2016 引入了
Object.keys和for.. in循环的迭代顺序和规范:19.1.2.16 (Object.keys) 调用 7.3。 21 (EnumerateOwnProperties) 反过来保证:“对属性的元素进行排序,使其与迭代器生成的相对顺序相同,如果使用 O 调用 EnumerateObjectProperties 内部方法,则返回该迭代器。” - EnumerateOwnProperties 反过来保证[[OwnPropertyKeys]](9.1.11) 保证顺序的 9.1.11.1 (ordinaryownpropertykeys)。 -
这些数字来自 ES2017 规范 (8),可以在这里免费找到:ecma-international.org/ecma-262/8.0
-
@BenjaminGruenbaum 我看不出13.7.5.15 EnumerateObjectProperties 在哪里保证与[[OwnPropertyKeys]] 相同的顺序。它只说“...必须通过调用[the] internal method来获取自己的属性键[...]”。获取后如何处理它们,或者它们如何与继承的属性合并,留给实现。