您的当前位置:首页正文

[ECMAScript] Object.keys的枚举顺序

来源:华佗小知识

1. 属性列表

  1. Let obj be ? ToObject(O).
  2. Let nameList be ? EnumerableOwnProperties(obj, "key").
  3. Return CreateArrayFromList(nameList).
  1. Assert: Type(O) is Object.
  2. Let ownKeys be ? O.[[OwnPropertyKeys]]().
  3. Let properties be a new empty List.
  4. For each element key of ownKeys in List order, do
    4.1 If Type(key) is String, then
    4.1.1 Let desc be ? O.[[GetOwnProperty]](key).
    4.1.2 If desc is not undefined and desc.[[Enumerable]] is true, then
    4.1.2.1 If kind is "key", append key to properties.
    4.1.2.2 Else,
    4.1.2.2.1 Let value be ? Get(O, key).
    4.1.2.2.2 If kind is "value", append value to properties.
    4.1.2.2.3 Else,
    4.1.2.2.3.1 Assert: kind is "key+value".
    4.1.2.2.3.2 Let entry be CreateArrayFromList(« key, value »).
    4.1.2.2.3.3 Append entry to properties.
  5. Order the elements of properties so they are in the same relative order as would be produced by the Iterator that would be returned if the EnumerateObjectProperties internal method were invoked with O.
  6. Return properties.
  1. Return ! OrdinaryOwnPropertyKeys(O).
  1. Let keys be a new empty List.
  2. For each own property key P of O that is an integer index, in ascending numeric index order, do
    2.1 Add P as the last element of keys.
  3. For each own property key P of O that is a String but is not an integer index, in ascending chronological order of property creation, do
    3.1 Add P as the last element of keys.
  4. For each own property key P of O that is a Symbol, in ascending chronological order of property creation, do
    4.1 Add P as the last element of keys.
  5. Return keys.

注:
Object.keys是ES 5(ECMAScript 2009)引入的特性,
经历了ES 5.1(ECMAScript 2011),返回的属性列表都是与具体实现相关的。

后来,在ES 6(ECMAScript 2015)中规定了上述枚举顺序,
然后到ES 7(ECMAScript 2016),ES 8(ECMAScript 2017),沿用至今。

2. 例子

x = {b:20, 3:2, [Symbol('A')]:2, a:100, 2:1};
> Object {2: 1, 3: 2, b: 20, a: 100, Symbol(A): 2}

Object.keys(x);
> ["2", "3", "b", "a"]

此外,在控制台上交互式的展开对象的属性,则只能看到对象的可枚举属性。

 ↓ Object {2: 1, 3: 2, b: 20, a: 100, Symbol(A): 2}
    2: 1
    3: 2
    a: 100
    b: 20
    Symbol(A): 2
    __proto__: Object


参考