Object.getOwnPropertySymbols() 方法返回给定对象中找到的所有符号属性的数组。
示例
const symbol1 = Symbol('symbol1');
const symbol2 = Symbol('symbol2');
const obj = {
property1: 'value1',
[symbol1]: 'value2',
[symbol2]: 'value3'
};
// get all the symbols of the obj
const symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols);
// Output: [ Symbol(symbol1), Symbol(symbol2) ]
getOwnPropertySymbols() 语法
getOwnPropertySymbols()
方法的语法是:
Object.getOwnPropertySymbols(obj)
在这里,getOwnPropertySymbols()
是一个静态方法。因此,我们需要使用类名 Object
来访问该方法。
getOwnPropertySymbols() 参数
getOwnPropertySymbols()
方法接受:
- obj - 要返回其符号属性的对象。
getOwnPropertySymbols() 返回值
getOwnPropertySymbols()
方法返回给定对象中找到的所有符号属性的数组。
注意: Object.getOwnPropertySymbols()
返回对象的所有符号属性,而 Object.getOwnPropertyNames() 返回字符串属性。
示例:JavaScript Object.getOwnPropertySymbols()
// create a symbol id
let id = Symbol("id");
// create a symbol name
let name = Symbol("name");
// create an object with
// symbol keys: id and name
// and string key: age
let superhero1 = {
[id]: 102,
[name]: "Bruce Wayne",
age: 40
};
// get all symbols of superhero1
let objectSymbols = Object.getOwnPropertySymbols(superhero1);
// print the symbols
console.log(objectSymbols);
// Output: [ Symbol(id), Symbol(name) ]
在上面的程序中,我们创建了一个对象 superhero1,它具有以下属性:
- 符号 - id 和 name
- 字符串 - age
然后,我们对 superhero1 使用了 getOwnPropertySymbols()
方法来列出其符号属性。
正如预期的那样,我们得到的输出是一个仅包含 id 和 name 符号的数组。
另请阅读