在ES6中的符号上有一个.toString(),它返回Symbol的字符串表示,但想知道为什么”Symbol()不起作用(运行此表达式会抛出TypeError,我不期望)?后者只是在新的Symbol上调用.toString()并将它追加()为空字符串吗?
解决方法
Is the latter just calling
.toString()
on a newSymbol
and append (+
) it to empty string?
实际上,符号不能隐式地转换为字符串或数字,尽管有趣的是,你可以隐式地将它们转换为布尔值.
关于其中一些陷阱的MDN actually has a section:
Symbol type conversions
Some things to note when working with type conversion of symbols.
- When trying to convert a symbol to a number,a
TypeError
will be thrown (e.g.+sym
orsym | 0
).- When using loose equality,
Object(sym) == sym
returnstrue.
Symbol("foo") + "bar"
throws aTypeError
(can’t convert symbol to string). This prevents you from silently creating a new string property name from a symbol,for example.- The “safer”
String(sym)
conversion works like a call toSymbol.prototype.toString()
with symbols,but note thatnew String(sym)
will throw.
此行为记录在abstract ToString
operation下的规范中:
Argument Type: Symbol
Result: Throw a
TypeError
exception.
同样适用于abstract ToNumber
operation:
Argument Type: Symbol
Result: Throw a
TypeError
exception.
要将Symbol转换为没有TypeError的字符串,必须使用toString方法或String().