有人可以详细解释这里发生了什么吗?特别是双点符号。这是什么JavaScript语法?
(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"
(3).toFixed(); // "3"
3.toFixed(); // SyntaxError: Unexpected token ILLEGAL
3..toFixed(); // "3"
有人可以详细解释这里发生了什么吗?特别是双点符号。这是什么JavaScript语法?
(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"
(3).toFixed(); // "3"
3.toFixed(); // SyntaxError: Unexpected token ILLEGAL
3..toFixed(); // "3"
据ECMA Script 5.1 Specifications,语法为十进制文本被定义这样
DecimalLiteral :: DecimalIntegerLiteral . [DecimalDigits] [ExponentPart] . DecimalDigits [ExponentPart] DecimalIntegerLiteral [ExponentPart]
注:方括号只是为了表明部分是可选的。
所以,当你说
3.toFixed()
消费3.
后,解析器认为,当前标记是一个十进制文字的一部分,但它只能跟着DecimalDigits
或ExponentPart
。但它发现t
,这是无效的,这就是为什么它与语法错误失败。
当你做
3..toFixed()
消费3.
后,它看到.
被称为属性存取操作。因此,它省略了可选的DecimalDigits
和ExponentPart
并构造了浮点对象并继续调用toFixed()
方法。克服这种
一种方法是在数字后面留下一个空间,这样
3 .toFixed()
3.
是一个数字,所以.
是小数点和不启动的属性。
3..something
是一个数字后跟一个属性。