为什么符号不能隐式转换字符串 [英] Why Symbols not convert string implicitly

查看:39
本文介绍了为什么符号不能隐式转换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Symbol('test').toString()效果很好,但是我不能使用''+ Symbol('test')?

Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?

它将抛出错误:

无法将符号值转换为字符串

cannot convert a Symbol value to a string

为什么隐式类型转换不起作用?为什么代码不等于''+ Symbol('test').toString()?

Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

推荐答案

根据ECMA-262,使用 ToString ,对于Symbols,它将抛出TypeError异常.

According to ECMA-262, using the addition operator on a value of type Symbol in combination with a string value first calls the internal ToPrimitive, which returns the symbol. It then calls the internal ToString which, for Symbols, will throw a TypeError exception.

因此,调用内部 ToString 与调用

So calling the internal ToString is not the same as calling Symbol.prototype.toString.

所以我想答案是

为什么隐式类型转换不起作用?

Why does the implicit type conversion not work?

是"因为规范是这样".

这篇关于为什么符号不能隐式转换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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