问题描述
ES6中的Symbol
上有一个.toString()
,它返回Symbol
的字符串表示形式,但是想知道为什么'' + Symbol()
不起作用(运行此表达式会抛出TypeError
,这是我所不希望的) )?后者只是在新的Symbol
上调用.toString()
并将其附加(+
)到空字符串吗?
There is a .toString()
on Symbol
in ES6 which returns the string representation of Symbol
, but wondering why '' + Symbol()
doesn't work (run this expression throws out TypeError
which I don't expect)? Is the latter just calling .toString()
on a new Symbol
and append (+
) it to empty string?
推荐答案
实际上,即使将符号隐式转换为布尔值,也不能将符号隐式转换为字符串或数字.
No actually, Symbols cannot be implicitly cast to strings, or numbers, although interestingly enough you can implicitly cast them to a boolean.
MDN实际上其中有一部分陷阱:
使用符号类型转换时要注意一些事情.
Some things to note when working with type conversion of symbols.
- 尝试将符号转换为数字时,将抛出
TypeError
(例如+sym
或sym | 0
). - 使用宽松等式时,
Object(sym) == sym
返回true.
-
Symbol("foo") + "bar"
引发TypeError
(无法将符号转换为字符串).例如,这可以防止您从符号中静默创建新的字符串属性名称. - 更安全"的
String(sym)
转换的工作方式类似于带符号的Symbol.prototype.toString()
调用,但请注意,new String(sym)
会抛出.
- 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.
此行为记录在规范中的抽象ToString
操作下:
This behavior is documented in the spec under the abstract ToString
operation:
结果:引发TypeError
异常.
对于抽象ToNumber
操作:
结果:引发TypeError
异常.
要将Symbol
强制转换为没有TypeError
的字符串,必须使用toString
方法或String()
.
To cast a Symbol
to a string without a TypeError
, you must use either the toString
method, or String()
.
这篇关于为什么隐式Symbol到String的转换会导致JavaScript中的TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!