为什么10..toString()有效,但10.toString()不起作用? [英] Why does 10..toString() work, but 10.toString() does not?
问题描述
可能重复:
在JavaScript中使用toString
152..toString(2)
正确创建二进制字符串10011000,但
correctly creates the binary string "10011000", but
152.toString(2)
抛出异常
语法错误:标识符在数字文字后立即启动
"SyntaxError: identifier starts immediately after numeric literal"
为什么?后一种语法实际上听起来更正确,而前者看起来很奇怪!
Why? The latter syntax actually sounds more correct while the former looks very odd!
推荐答案
A 。
在一个数字看似含糊不清之后。它是小数还是对象成员运算符?
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 and downvoters
。
字符会出现歧义。可以理解为成员运算符或小数,具体取决于其位置。如果没有歧义,那就毫无疑问。
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解释器的歧义,并不意味着<$ c的模糊性$ c>。字符根本不存在。
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屋!