符号字符串强制

Symbol string coercion

Symbol() + '' 抛出

TypeError: Cannot convert a Symbol value to a string

虽然已知的解决方法是使用 String(Symbol()).

这看起来与其他原语不一致,包括那些几乎不应该被强制转换的原语(undefinednull)。

String+ '' 究竟有何不同(除了有效)?规范是否明确指定 String 应该接受符号?以一种方式允许它而以另一种方式不允许它的动机是什么?

How exactly does String differ from + '' (except it works)? Do specs explicitly specify that String should accept symbols?

它们的不同之处在于 String()Symbol() 的情况,而 + 运算符(当用于连接时)直接调用 ToString() 操作对于 Symbol().

抛出 TypeError 异常

来自 String() 规格:

If NewTarget is undefined and Type(value) is Symbol, return SymbolDescriptiveString(value).

来自+评估规范:

If Type(lprim) is String or Type(rprim) is String, then

  • Let lstr be ToString(lprim).
    • ReturnIfAbrupt(lstr).
    • Let rstr be ToString(rprim).
    • ReturnIfAbrupt(rstr).
    • Return the String that is the result of concatenating lstr and rstr.

注意:lprimrprim 的定义来自评估过程中的前 10 个步骤,这些步骤涉及获取原始类型和表达式两侧的值。我没有包括它们是为了使 post 更短。我已经链接了我在下面引用的每个规范。

来自 ToString() 输出:

Symbol: Throw a TypeError exception.

关于你的最后一个问题:

What were the motives to allow it in one way and disallow it in another?

这是 ECMA International 的作者们的事。

String() ES6 Spec

+ operator runtime evaluation ES6 Spec

ToString() Output behavior ES6 Spec