符号字符串强制 [英] Symbol string coercion

查看:134
本文介绍了符号字符串强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

符号()+''抛出


TypeError:无法转换a符号值为字符串

TypeError: Cannot convert a Symbol value to a string

虽然已知的解决方法是使用字符串(符号())

While a known workaround is to use String(Symbol()).

这看起来与其他原语不一致,包括那些几乎永远不会被强制的原语( undefined null )。

This looks inconsistent with other primitives, including the ones that should almost never be coerced (undefined and null).

字符串到底是怎么回事?不同于 +''(除了它有效)?规范是否明确指定 String 应该接受符号?以一种方式允许它并在另一种方式中禁止它的动机是什么?

How exactly does String differ from + '' (except it works)? Do specs explicitly specify that String should accept symbols? What were the motives to allow it in one way and disallow it in another?

推荐答案


究竟如何?字符串与+''不同(除了它有效)?规范是否明确指定String应该接受符号?

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

它们在 String()有一个 Symbol()的情况,而 + 运算符(当用于连接时)直接调用 ToString()操作,该操作为符号()<抛出 TypeError 异常/ code>。

They differ in the aspect that String() has a case for a Symbol(), whereas the + operator (when used for concatenation) directly calls the ToString() operation which throws a TypeError exception for a Symbol().

来自字符串()规格:


如果NewTarget未定义且Type(value)为Symbol,则返回SymbolDescriptiveString(value)。

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

来自 + 评估规范:


如果Type(lprim)是字符串或类型(rprim)是String,然后

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


  • 让lstr成为ToString(lprim)。


    • ReturnIfAbrupt(lstr)。

    • 让rstr成为ToString(rprim)。

    • ReturnIfAbrupt(rstr)。

    • 返回串联lstr和rstr的结果的字符串。

    • 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.

      注意: lprim rprim 来自评估过程中的前10个步骤,其中涉及获取表达式边的基本类型和值。我没有包括它们以保持这篇文章更短。我已经链接了我在下面引用的每个规范。

      Note: the definitions for lprim and rprim come from 10 previous steps in the evaluation process, which involve getting primitive types and values of the sides of the expression. I didn't include them to keep this post shorter. I have linked each specification I have referenced below.

      ToString()输出:


      符号:抛出TypeError异常。

      Symbol: Throw a TypeError exception.

      至于你的最后一个问题:

      As for your final question:


      以一种方式允许它而在另一种方式允许它的动机是什么?

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

      这是ECMA国际作家的作品。

      That's something for the writers at ECMA International.

      String()ES6 Spec

      +运营商运行时评估ES6规范

      ToString( )输出行为ES6规范

      这篇关于符号字符串强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆