Get the description of a ES6 Symbol

余生颓废 提交于 2019-12-17 06:50:15

问题


I wonder if there is a nice way to get the descriptions of a Symbol.

For example,

var s = Symbol(5);

The default implementation of the toString will simply print Symbol(5)

I would like to find a way to extract the actual description i.e. 5


回答1:


Symbol.description returns description of the symbol. Simply do s.description in your case.

REF: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description




回答2:


 String(symbol).slice(7, -1) || null

This works because String(symbol) explicitly coerce the symbol into a string e.g. Symbol('test') gets coerced into "Symbol(test)".

Doing a splicing on the from 7 to -1 does a splicing between the two brackets, thus capturing the description test

Note: that this may not work for object descriptions (e.g. Symbol({test})) as objects gets coerced into "[object Object]"




回答3:


There is no neat way to do this. However, if you have registered a symbol in the global registry, you can use Symbol.keyFor():

var s = Symbol.for(5);
console.log(Symbol.keyFor(s));



回答4:


symbol-description package on npm

Returns description of provided symbol:

const symDesc = require('symbol-description')
symDesc(Symbol('foo')) // foo

It was published by me just now after reading this answer here.



来源:https://stackoverflow.com/questions/30301728/get-the-description-of-a-es6-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!