我想知道,这是合法的吗?
function test() { alert ("hello") $("#loading").show(); }
或者我应该写这个:
function test() { alert ("hello"); $("#loading").show(); }
JavaScript中的分号是否可选?因为我在论坛中看到了这个:
No,semicolons are usually optional in JavaScript (google for ASI / automatic semicolon insertion). Using them makes the code look much cleaner though and ASI is a horrible mis-feature (at least in my opinion).
解决方法
Certain ECMAScript statements (empty statement,variable statement,
expression statement,do-while statement,continue statement,break
statement,return statement,and throw statement) must be terminated
with semicolons. Such semicolons may always appear explicitly in the
source text. For convenience,however,such semicolons may be omitted
from the source text in certain situations. These situations are
described by saying that semicolons are automatically inserted into
the source code token stream in those situations.
更新(进一步解释)
也许最常见的情况用于说明为什么自动分号插入可能是坏的,这是@sissonb在另一个答案中所触及的.考虑以下:
function something(a,b) { return a + b; }
你可能期望的是新行被忽略,代码解释为:
function something(a,b) { return a + b; }
function something(a,b) { return; a + b; }
并且一个空的return语句意味着该函数返回undefined.因此,不是两个参数的一个很好的总和,你得到未定义,并可能最终混淆你出错的地方!这就是为什么我完全同意你的问题中的声明,即自动分号插入是一个可怕的错误.
> Example (returns undefined
because of ASI).
> Example (returns expected result).