[英]Why does adding a semicolon sometimes break an if statement?
Why is it that you aren't supposed to add semicolons after every set of curly braces? 为什么不应该在每组花括号之后添加分号? I thought this was a rule in JavaScript.
我认为这是JavaScript中的规则。 In this code snippet, for instance, it turns out that it does not work because of the semicolon after the initial if statement, but then the semicolon after the else statement is fine.
例如,在此代码段中,由于在初始if语句之后使用分号,但在else语句之后使用分号就可以了,因此它不起作用。
function a() { if (var >= length) { count = var / length; }; else { count = 0 };
Adding the semicolon between the if
and else
effectively splits them into two separate blocks. 在
if
和else
之间添加分号可将它们有效地分成两个单独的块。
An if
block can exist on its own, but not an else
block, since the else
depends on the condition in the if
statement. if
块可以单独存在,但else
块不能存在,因为else
取决于if
语句中的条件。
Because the entire expression includes the if
block. 因为整个表达式都包含
if
块。 Semi-colons are introduced after the completion of an expression (and not necessary post if
curly braces). 分号是在表达式完成后引入的(
if
花括号, if
不必在分号后加上)。 When you add a semi-colon after the if
, you are cutting the entire expression short. 在
if
后面添加分号if
,将缩短整个表达式。
You are, in a sense, saying: 从某种意义上讲,您是在说:
if (foo === bar) {
//do something
} /** You: Ok stop doing stuff**/;
/**
Javascript: Ok! I'm done
**/
else { // Javascript: Wait, what is this crap
//nothing's gonna happen
}
The semicolon after the first }
creates an empty statement. 第一个
}
之后的分号创建一个空语句。 It's as if you wrote: 就像您写了一样:
alert('test');
;
This extra "empty" statement separates the if
from the else
, so the else
block becomes meaningless. 这个额外的“空”语句将
if
与else
分开,因此else
块变得毫无意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.