根据 this , JavaScript 将在以下情况下插入分号:
When the program contains a token that is not allowed by the formal grammar, then a semicolon is inserted if (a) there is a line break at that point, or (b) the unexpected token was a closing brace. (emphasis mine)
经典的例子是
return // <--- semicolon inserted there
{
id: 12
};
这让我相信独立的 {
是无效的。然而以下(无意义的)代码警告 2,没有错误
function foo() {
var x = 1;
{
var y = 2; //yes, I know y has the same scope as x
} //and that this is therefore pointless
alert(y);
}
为什么左大括号在第一段代码中被视为无效标记,导致 JavaScript 插入分号,但在第二段代码中左大括号未被视为无效——事实证明没有错误。
显然我的一个假设是错误的,我希望有人能帮助我理解是哪一个。
最佳答案
您提到的 return
语句问题不受分号插入规则的那个特定方面的影响。相反,是这个:
When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation ―[no LineTerminator here]‖ within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.
碰巧 return
语句语法有一个“[这里没有 LineTerminator]”怪癖。
请参阅 ES 5 规范的第 7.9.1 节。
关于javascript - 难以理解分号插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8393677/