js对象遍历顺序问题?

用Object.keys遍历对象key,如果对象中不包含key为number类型的话能否保持遍历顺序?现在要改代码话发现要改的地方挺多.

回答

参见

非数组下标型的 key 是按创建时间返回的,所以应该是不能。

js对象遍历顺序问题?

ECMA-262的官方描述:

9.1.11 [[OwnPropertyKeys]] ( )

When the [[OwnPropertyKeys]] internal method of O is called, the following steps are taken:

1. Return ! OrdinaryOwnPropertyKeys(O).

9.1.11.1 OrdinaryOwnPropertyKeys ( O )

When the abstract operation OrdinaryOwnPropertyKeys is called with Object O, the following steps are taken:

1. Let keys be a new empty List.

2. For each own property key P of O such that P is an array index, in ascending numeric index order, do

a. Add P as the last element of keys.

3. For each own property key P of O such that Type(P) is String and P is not an array index, in ascending

chronological order of property creation, do

a. Add P as the last element of keys.

4. For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property

creation, do

a. Add P as the last element of keys.

5. Return keys.

对象键是没有顺序的,ES6 Map 的 keys 会按插入顺序

以上是 js对象遍历顺序问题? 的全部内容, 来源链接: utcz.com/a/66149.html

回到顶部