Reflect.ownKeys()
Reflect.ownKeys() 静态方法返回 target 对象自身属性键的数组。
试一试
const object = {
property1: 42,
property2: 13,
};
const array = [];
console.log(Reflect.ownKeys(object));
// Expected output: Array ["property1", "property2"]
console.log(Reflect.ownKeys(array));
// Expected output: Array ["length"]
语法
js
Reflect.ownKeys(target)
参数
目标-
要从中获取自身键的目标对象。
返回值
一个包含 target 对象自身属性键的 Array,包括字符串和 Symbol。对于大多数对象,数组的顺序如下:
- 非负整数索引,按递增的数字顺序(但作为字符串)
- 其他字符串键,按属性创建顺序
- Symbol 键,按属性创建顺序。
异常
TypeError-
如果
target不是一个对象,则抛出。
描述
Reflect.ownKeys() 提供了检索对象所有属性键的反射语义。它是唯一一种可以通过一次调用获取所有自身属性——可枚举和不可枚举、字符串和 Symbol——而不进行额外过滤的方法。例如,Object.getOwnPropertyNames() 使用 Reflect.ownKeys() 的返回值并过滤出仅包含字符串值,而 Object.getOwnPropertySymbols() 则过滤出仅包含 Symbol 值。由于普通对象实现 [[OwnPropertyKeys]] 以在 Symbol 键之前返回所有字符串键,因此 Reflect.ownKeys(target) 通常等同于 Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))。但是,如果对象具有自定义的 [[OwnPropertyKeys]] 方法(例如通过代理的 ownKeys 处理器),则键的顺序可能会有所不同。
Reflect.ownKeys() 调用 target 的 [[OwnPropertyKeys]] 对象内部方法。
示例
使用 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
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-reflect.ownkeys |
浏览器兼容性
加载中…