Object.getOwnPropertySymbols()

Object.getOwnPropertySymbols() 静态方法返回直接在给定对象上找到的所有符号属性的数组。

¥The Object.getOwnPropertySymbols() static method returns an array of all symbol properties found directly upon a given object.

Try it

语法

¥Syntax

js
Object.getOwnPropertySymbols(obj)

参数

¥Parameters

obj

要返回其符号属性的对象。

返回值

¥Return value

直接在给定对象上找到的所有符号属性的数组。

¥An array of all symbol properties found directly upon the given object.

描述

¥Description

Object.getOwnPropertyNames() 类似,你可以获取给定对象的所有符号属性作为符号数组。请注意,Object.getOwnPropertyNames() 本身不包含对象的符号属性,仅包含字符串属性。

¥Similar to Object.getOwnPropertyNames(), you can get all symbol properties of a given object as an array of symbols. Note that Object.getOwnPropertyNames() itself does not contain the symbol properties of an object and only the string properties.

由于所有对象最初都没有自己的符号属性,因此 Object.getOwnPropertySymbols() 返回一个空数组,除非你在对象上设置了符号属性。

¥As all objects have no own symbol properties initially, Object.getOwnPropertySymbols() returns an empty array unless you have set symbol properties on your object.

示例

¥Examples

使用 Object.getOwnPropertySymbols()

¥Using Object.getOwnPropertySymbols()

js
const obj = {};
const a = Symbol("a");
const b = Symbol.for("b");

obj[a] = "localSymbol";
obj[b] = "globalSymbol";

const objectSymbols = Object.getOwnPropertySymbols(obj);

console.log(objectSymbols.length); // 2
console.log(objectSymbols); // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0]); // Symbol(a)

规范

Specification
ECMAScript Language Specification
# sec-object.getownpropertysymbols

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看