Javascript weird dot operator syntax [duplicate]

与世无争的帅哥 提交于 2019-12-25 09:19:48

问题


In Chrome console, also test in edge and firefox

5.toFixed(2);

get

Uncaught SyntaxError: Invalid or unexpected token

in chrome.

SyntaxError: identifier starts immediately after numeric literal

in firefox.

Expected ';'

in edge.

But code below

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

is ok in all three browsers above.


回答1:


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.

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).

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.



来源:https://stackoverflow.com/questions/40297507/javascript-weird-dot-operator-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!