为什么隐式Symbol到String的转换会导致JavaScript中的TypeError? [英] Why does implicit Symbol to String conversion' lead to TypeError in JavaScript?

查看:242
本文介绍了为什么隐式Symbol到String的转换会导致JavaScript中的TypeError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

后者只是在新的Symbol上调用.toString()并将其附加(+)到空字符串吗?

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(例如+symsym | 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 or sym | 0).
  • When using loose equality, Object(sym) == sym returns true.
  • Symbol("foo") + "bar" throws a TypeError (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 to Symbol.prototype.toString() with symbols, but note that new 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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