为什么 10..toString() 有效,而 10.toString() 无效? [英] Why does 10..toString() work, but 10.toString() does not?

查看:21
本文介绍了为什么 10..toString() 有效,而 10.toString() 无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
toString 在 JavaScript 中的使用

152..toString(2)

正确创建二进制字符串10011000",但是

correctly creates the binary string "10011000", but

152.toString(2)

抛出异常

SyntaxError:标识符在数字文字之后立即开始"

"SyntaxError: identifier starts immediately after numeric literal"

为什么?后者的语法实际上听起来更正确,而前者看起来很奇怪!

Why? The latter syntax actually sounds more correct while the former looks very odd!

推荐答案

一个 . 在数字之后可能看起来不明确.它是十进制还是对象成员运算符?

A . after a number might seem ambiguous. Is it a decimal or an object member operator?

然而,解释器决定它是一个小数,所以你缺少成员运算符.

However, the interpreter decides that it's a decimal, so you're missing the member operator.

它是这样看的:

(10.)toString();  // invalid syntax

当您包含第二个 . 时,您有一个小数,后跟成员运算符.

When you include the second ., you have a decimal followed by the member operator.

(10.).toString();

<小时>

@pedants 和反对者

. 字符 表示歧义.可以理解为成员运算符,也可以理解为小数,这取决于它的位置.如果没有歧义,就没有问题要问了.

The . character presents an ambiguity. It can be understood to be the member operator, or a decimal, depending on its placement. If there was no ambiguity, there would be no question to ask.

规范对那个特定位置的 . 字符的解释是它将是一个小数.这是由 ECMAScript 的数字文字语法定义的.

The specification's interpretation of the . character in that particular position is that it will be a decimal. This is defined by the numeric literal syntax of ECMAScript.

仅仅因为规范为 JS 解释器解决了歧义,并不意味着 . 字符的歧义根本不存在.

Just because the specification resolves the ambiguity for the JS interpreter, doesn't mean that the ambiguity of the . character doesn't exist at all.

这篇关于为什么 10..toString() 有效,而 10.toString() 无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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