Javascript怪异的点运算符语法 [英] Javascript weird dot operator syntax

查看:111
本文介绍了Javascript怪异的点运算符语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome控制台中,还可以在Edge和Firefox中进行测试

In Chrome console, also test in edge and firefox

5.toFixed(2);

获取

未捕获的SyntaxError:无效或意外的令牌

Uncaught SyntaxError: Invalid or unexpected token

在镀铬中.

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

SyntaxError: identifier starts immediately after numeric literal

在Firefox中.

预期为';'

Expected ';'

处于边缘.

但是下面的代码

5.1.toFixed(2);
(5).toFixed(2);

在以上所有三个浏览器中

都可以.

is ok in all three browsers above.

推荐答案

这是因为JavaScript解析器假定例如5.toFixed(2)中的点属于数字文字. (与5.中一样,这是有效的数字文字.)这是因为JavaScript贪婪地解析(至少是数字文字).

This is because of the JavaScript parser assuming the dot in for example 5.toFixed(2) belongs the number literal. (As in 5., which is a valid number literal.) This is because JavaScript parses (at least number literals) greedily.

但是,如果您执行(5).toFixed(2),则解析器很清楚想要什么(点显然不是数字文字的一部分).

If you do (5).toFixed(2) however, it is clear to the parser what you want (the dot clearly is not a part of the number literal).

5.1.toFixed(2)相同.第二个点显然不能属于数字文字,因此解析器拥有更好的时间.

Same with 5.1.toFixed(2). The second dot clearly cannot belong to the number literal, so the parser has a better time with it.

这篇关于Javascript怪异的点运算符语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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