js对象遍历顺序问题?

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

阅读 4.7k
3 个回答

参见

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

image

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.

1、使用数组下标会按照下标升序返回

其实数字就是数组下标
let u1 = {
    1: 'name';
}
这里的 'name' 就是 u1 的数组下标 1 的值

2、使用字符串按创建时间返回
3、使用符号按创建时间返回

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题