将JavaScript符号转换为字符串?

前端之家收集整理的这篇文章主要介绍了将JavaScript符号转换为字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在ES6中的符号上有一个.toString(),它返回Symbol的字符串表示,但想知道为什么”Symbol()不起作用(运行此表达式会抛出TypeError,我不期望)?后者只是在新的Symbol上调用.toString()并将它追加()为空字符串吗?

解决方法

Is the latter just calling .toString() on a new Symbol and append (+) it to empty string?

实际上,符号不能隐式地转换为字符串或数字,尽管有趣的是,你可以隐式地将它们转换为布尔值.

关于其中一些陷阱的MDN actually has a section

Symbol type conversions

Some things to note when working with type conversion of symbols.

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

此行为记录在abstract ToString operation下的规范中:

Argument Type: Symbol

Result: Throw a TypeError exception.

同样适用于abstract ToNumber operation

Argument Type: Symbol

Result: Throw a TypeError exception.

要将Symbol转换为没有TypeError的字符串,必须使用toString方法或String().

原文链接:https://www.f2er.com/js/158863.html

猜你在找的JavaScript相关文章