简体   繁体   English

为什么添加分号有时会破坏if语句?

[英]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. ifelse之间添加分号可将它们有效地分成两个单独的块。

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. 这个额外的“空”语句将ifelse分开,因此else块变得毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不使用分号会破坏此代码? - Why does leaving off a semicolon break this code? 尽管我使用了 break 语句,为什么我的 for 循环有时会执行两次? - Why does my for loop sometimes execute twice, despite my use of a break statement? 为什么此语句需要分号? - Why is semicolon required for this statement? 为什么 return 语句不会破坏 Javascript 中的递归循环 - why does return statement not break recursive for loop in Javascript 为什么在javascript中向Array原型添加方法会中断for循环上的迭代? - Why does adding a method to the Array prototype in javascript break iteration on a for loop? 为什么添加 crossOrigin 会破坏 fabric.Image.fromURL? - Why does adding crossOrigin break fabric.Image.fromURL? 为什么在DDO工厂功能中添加参数会破坏应用程序? - Why does adding a parameter to DDO factory function break the app? 我在一个for循环中有两个if语句,为什么有时在第一个语句之前运行第二个if语句? - I have two if statements inside one for loop, why does it sometimes run the second if statement before the first statement? 为什么JSLint表示此jQuery中缺少分号? - Why does JSLint say there is a missing semicolon in this jQuery? 为什么JavaScript for循环中的迭代器不需要分号? - Why does the iterator in a JavaScript for loop not need a semicolon?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM