我在 NodeJS 中有一个对象(准确地说是一个套接字)。
当我打印它时,我看到其中一个条目是这样的:
[Symbol(asyncId)]: 2781 // the numeric value changes
如何获取该键的值?
我已经尝试了 socket['[Symbol(asyncId)]']
但得到了 undefined
。
表达式 socket.[Symbol(asyncId)]
显然不起作用。
最佳答案
您将无法通过键直接访问它,除非您有对实际的引用:Symbol('asyncId')
,因为每个 Symbol 都是唯一
The Symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class but is incomplete as a constructor because it does not support the syntax "new Symbol()".
您可以使用 Reflect.ownKeys 遍历对象自身的属性键,其中将包含普通属性和符号,然后获取该引用。
您还可以使用:Object.getOwnPropertySymbols()
function getObject() {
// You don't have access to this symbol, outside of this scope.
const symbol = Symbol('asyncId');
return {
foo: 'bar',
[symbol]: 42
};
}
const obj = getObject();
console.log(obj);
console.log(obj[Symbol('asyncId')]); // undefined
// or Object.getOwnPropertySymbols(obj)
const symbolKey = Reflect.ownKeys(obj)
.find(key => key.toString() === 'Symbol(asyncId)')
console.log(obj[symbolKey]); // 42
注意:对象可以有多个键,其中 key.toString() === 'Symbol(asyncId)'
,这不是通常情况,但可以意识到,所以你可能想使用 .find
以外的其他功能,如果是这种情况。
注意二: 您不应更改该属性的值,因为它应该仅供内部访问,即使该属性不是只读的也是如此。
function getObject() {
// You don't have access to this symbol, outside of this scope.
const symbol = Symbol('asyncId');
const symbol2 = Symbol('asyncId');
return {
foo: 'bar',
[symbol]: 'the value I don\'t want',
[symbol2]: 'the value I want'
};
}
const obj = getObject();
const symbolKey = Reflect.ownKeys(obj)
.find(key => key.toString() === 'Symbol(asyncId)')
console.log(obj[symbolKey]); // the value I don't want
console.log('=== All values ===');
Reflect.ownKeys(obj)
.forEach(key => console.log(obj[key]));
关于javascript - 如何获取 Symbol 属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50453640/