Reflect.ownKeys()

Reflect.ownKeys() 静态方法返回 target 对象自己的属性键的数组。

¥The Reflect.ownKeys() static method returns an array of the target object's own property keys.

Try it

语法

¥Syntax

js
Reflect.ownKeys(target)

参数

¥Parameters

target

从中获取自己的密钥的目标对象。

返回值

¥Return value

target 对象自己的属性键的 Array,包括字符串和符号。对于大多数对象,数组的顺序为:

¥An Array of the target object's own property keys, including strings and symbols. For most objects, the array will be in the order of:

  1. 按递增数字顺序排列的非负整数索引(但作为字符串)
  2. 按属性创建顺序排列的其他字符串键
  3. 符号键按属性创建的顺序排列。

例外情况

¥Exceptions

TypeError

如果 target 不是对象,则抛出该异常。

描述

¥Description

Reflect.ownKeys() 提供了检索对象的所有属性键的反射语义。这是在一次调用中获取所有自己的属性(可枚举和不可枚举、字符串和符号)的唯一方法,无需额外的过滤逻辑。例如,Object.getOwnPropertyNames() 采用 Reflect.ownKeys() 的返回值并仅过滤字符串值,而 Object.getOwnPropertySymbols() 仅过滤符号值。因为普通对象实现 [[OwnPropertyKeys]] 以返回符号键之前的所有字符串键,所以 Reflect.ownKeys(target) 通常等同于 Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))。但是,如果对象具有自定义 [[OwnPropertyKeys]] 方法(例如通过代理的 ownKeys 处理程序),则键的顺序可能会有所不同。

¥Reflect.ownKeys() provides the reflective semantic of retrieving all property keys of an object. It is the only way to get all own properties – enumerable and not enumerable, strings and symbols — in one call, without extra filtering logic. For example, Object.getOwnPropertyNames() takes the return value of Reflect.ownKeys() and filters to only string values, while Object.getOwnPropertySymbols() filters to only symbol values. Because normal objects implement [[OwnPropertyKeys]] to return all string keys before symbol keys, Reflect.ownKeys(target) is usually equivalent to Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)). However, if the object has a custom [[OwnPropertyKeys]] method (such as through a proxy's ownKeys handler), the order of the keys may be different.

Reflect.ownKeys() 调用 target[[OwnPropertyKeys]] 对象内部方法

¥Reflect.ownKeys() invokes the [[OwnPropertyKeys]] object internal method of target.

示例

¥Examples

使用 Reflect.ownKeys()

¥Using Reflect.ownKeys()

js
Reflect.ownKeys({ z: 3, y: 2, x: 1 }); // [ "z", "y", "x" ]
Reflect.ownKeys([]); // ["length"]

const sym = Symbol.for("comet");
const sym2 = Symbol.for("meteor");
const obj = {
  [sym]: 0,
  str: 0,
  773: 0,
  0: 0,
  [sym2]: 0,
  "-1": 0,
  8: 0,
  "second str": 0,
};
Reflect.ownKeys(obj);
// [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ]
// Indexes in numeric order,
// strings in insertion order,
// symbols in insertion order

规范

Specification
ECMAScript Language Specification
# sec-reflect.ownkeys

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看