为什么这个声明需要分号?

saw*_*awa 0 javascript

以下代码返回一个错误,指出"console.log(...)不是函数"

if (4<5) console.log('hi') 
(4<5) ? console.log('hi') : console.log('bye')
Run Code Online (Sandbox Code Playgroud)

以下代码不会返回任何错误

if (4<5) console.log('hi')
if (4<5) console.log('hi')
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

T.J*_*der 5

在第一行末尾没有分号的情况下,代码尝试使用第一行的返回值console.log作为函数并使用参数调用它4<5; 如果删除换行符,则更清楚:

if (4<5) console.log('hi')(4<5) ? console.log('hi') : console.log('bye')
//       ^^^^^^^^^^^^^^^^^^^^^^---- looks like calling `console.log` and then
//                                  using the result as a function
Run Code Online (Sandbox Code Playgroud)

每当你结合使用表达式语句来分离分号(这意味着你依赖于纠错机制1)时,就有可能发生这种情况.因为表达式语句本质上是表达式,所以如果解析器可以在前面的表达式或语句中使用它们,它就会.


FWIW,astexplorer.net是我最近发现的一个很酷的工具(感谢Babel项目).它是一个交互式语法树资源管理器,它可以使用几个解析器中的任何一个来解析您的代码,并告诉您它是如何被解析的.从github帐户开始,它是由我们自己的Felix Kling创建的.


1 引用Brendan Eich:

ASI(正式来说)是一种语法错误纠正程序.如果你开始编码就好像它是一个普遍的重要换行规则,你就会遇到麻烦.