将JavaScript符号转换为字符串? [英] Convert JavaScript Symbol to String?
问题描述
ES6中的符号
上有 .toString()
,返回字符串表示为符号
,但是想知道为什么''+ Symbol()
不起作用(运行此表达式抛出 TypeError
我不指望)后者只是在一个新的符号
上调用 .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?
推荐答案
后者只是调用
.toString()
在新的符号
和附加(+
)它为空字符串?
Is the latter just calling
.toString()
on a newSymbol
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。
-
符号(foo)+bar
throws a code> 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.
参数类型:符号
结果:抛出 TypeError
异常。
同样地,对于摘要 ToNumber
操作:
And similarly for abstract ToNumber
operation:
参数类型:符号
结果:抛出 TypeError
异常。
转换符号
到没有 TypeError
的字符串,您必须使用 toString
方法,或 String ()
。
To cast a Symbol
to a string without a TypeError
, you must use either the toString
method, or String()
.
这篇关于将JavaScript符号转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!