ES6 中的Symbol
上有一个.toString()
返回Symbol
的字符串表示,但是想知道为什么' ' + Symbol()
不起作用(运行此表达式会抛出 TypeError
,这是我不期望的)?后者是否只是在新的 Symbol
上调用 .toString()
并将其附加 (+
) 到空字符串?
最佳答案
Is the latter just calling
.toString()
on a newSymbol
and append (+
) it to empty string?
实际上,Symbols 不能隐式转换为字符串或数字,尽管有趣的是您可以将它们隐式转换为 bool 值。
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()
。
关于javascript - 为什么隐式符号到字符串转换会导致 JavaScript 中的 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944470/