Get the description of a ES6 Symbol

后端 未结 4 534
渐次进展
渐次进展 2020-11-29 10:11

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

4条回答
  •  星月不相逢
    2020-11-29 11:13

     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]"

提交回复
热议问题