What is the difference between Reflect.ownKeys(obj) and Object.keys(obj)?

后端 未结 4 1981
小蘑菇
小蘑菇 2021-02-01 01:08

Testing them out in a real simple case yields the same output:

const obj = {a: 5, b: 5};
console.log(Reflect.ownKeys(obj));
console.log(Object.keys(obj));

// Re         


        
4条回答
  •  再見小時候
    2021-02-01 01:37

    In addition to what the other answers have already mentioned, Reflect.ownKeys is also guaranteed by the specification to return keys (and symbols) in the following order:

    • Integer numeric keys, in ascending order (0, 1, 2)
    • String keys, in the order they were inserted onto the object
    • Symbol keys

    This order is required by the internal [[OwnPropertyKeys]] method which is invoked by Reflect.ownKeys.

    In contrast, Object.keys calls EnumerableOwnPropertyNames, which requires:

    1. 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.

    Where EnumerateObjectProperties explicitly does not specify any order in which the properties are returned:

    The mechanics and order of enumerating the properties is not specified

    So, if you want to be absolutely certain that, while iterating over object properties, you iterate in insertion order for non-numeric keys, make sure to use Reflect.ownKeys (or Object.getOwnPropertyNames, which also invokes [[OwnPropertyKeys]]).

    (All that said, while Object.keys, its variants, for..in loops, and JSON.stringify all officially iterate in an unspecified, implementation-dependant order, environments generally iterate in the same predictable order as Reflect.ownKeys anyway, luckily)

提交回复
热议问题