这是什么javascript语法? [英] What is this javascript syntax?

查看:40
本文介绍了这是什么javascript语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以详细解释这里发生了什么吗?特别是双点符号.

Can someone explain in detail what is going on here? Specifically the double dot notation.

(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"

(3).toFixed(); // "3"
3.toFixed(); // SyntaxError: Unexpected token ILLEGAL
3..toFixed(); // "3"    

推荐答案

根据 ECMA脚本5.1规范,像这样定义十进制文字的语法

According to ECMA Script 5.1 Specifications, grammar for decimal literals are defined like this

DecimalLiteral ::

   DecimalIntegerLiteral . [DecimalDigits] [ExponentPart]

   . DecimalDigits [ExponentPart]

   DecimalIntegerLiteral [ExponentPart]

注意:方括号仅表示这些部分是可选的.

Note: The square brackets are just to indicate that the parts are optional.

所以,当你说

3.toFixed()

在消耗了 3.之后,解析器认为当前令牌是Decimal Literal的一部分,但是只能跟随 DecimalDigits ExponentPart.但是它会找到 t ,这是无效的,这就是为什么它失败并显示 SyntaxError 的原因.

After consuming 3., the parser thinks that the current token is a part of a Decimal Literal, but it can only be followed by DecimalDigits or ExponentPart. But it finds t, which is not valid, that is why it fails with SyntaxError.

什么时候做

3..toFixed()

在消费了 3.之后,它会看到.,这称为属性访问器运算符.因此,它省略了可选的 DecimalDigits ExponentPart ,并构造了一个浮点对象,并继续调用 toFixed()方法.

After consuming 3., it sees . which is called property accessor operator. So, it omits the optional DecimalDigits and ExponentPart and constructs a Floating point object and proceeds to invoke toFixed() method.

克服此问题的一种方法是像这样在数字后留一个空格

One way to overcome this is to leave a space after the number, like this

3 .toFixed()

这篇关于这是什么javascript语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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