javascript 为什么在 if/else 语句之后不使用分号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17036135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:51:22  来源:igfitidea点击:

Why are semicolons not used after if/else statements?

javascriptif-statement

提问by Ronathan

I understand that it is good syntax to use semicolons after all statements in Javascript, but does any one know why if/else statements do not require them after the curly braces?

我知道在 Javascript 中的所有语句之后使用分号是一种很好的语法,但是有人知道为什么 if/else 语句在大括号之后不需要它们吗?

回答by invisal

  • Semicolon is used to end ONE statement
  • {and }begin and close a group of statements
  • 分号用于结束 ONE 语句
  • {}开始和关闭一组语句

Basically, an if-elsemust be followed by either a statement or a group of statements.

基本上, anif-else后面必须跟一个语句或一组语句。

if-elsefollowed by a statement:

if-else接着是一个声明:

if (condition) statement;
if (condition); // followed by a statement (an empty statement)

if-elsefollowed by group of statements:

if-else接着是一组语句:

if (condition) {
   statement;
   statement;
}

if (condition) {
   // followed by a group of statements of zero length
}

if-elsemust end with a ;if it is followed by a single statement. if-elsedoes not end with a ;when followed by a group of statements because ;is used to end a single statement, and is not used for ending a group of statements.

if-else必须以;if结尾,后跟单个语句。if-else不以;when 后跟一组语句;结束,因为用于结束单个语句,而不用于结束一组语句。

回答by Ira Baxter

The real answer is because many modern languages copied their syntax from C, which has this property. JavaScript is one of these languages.

真正的答案是因为许多现代语言从具有此属性的 C 复制了它们的语法。JavaScript 是这些语言之一。

C allows statement blocks

C 允许语句块

 { ... }

(which don't need terminating semicolons) to be used where statements can be used. So you can use statement blocks as then- and else- clauses, without the semicolons.

(不需要终止分号)在可以使用语句的地方使用。因此,您可以将语句块用作 then- 和 else- 子句,而无需使用分号。

If you place a singlestatement in the then- or else- clause, you'll need to terminate it with a semicolon. Again, just as in C, with the extra JavaScript twist that ; is optional at the end of a line, if inserting it would not cause a syntax error.

如果将单个语句放在 then- 或 else- 子句中,则需要用分号终止它。同样,就像在 C 中一样,额外的 JavaScript 扭曲是 ; 在行尾是可选的,如果插入它不会导致语法错误。

回答by Orangepill

Because the curly braces themselves are termination characters.

因为花括号本身就是终止符。

The are tokens that enclose a compound statement block and are intrinsically terminated. It's like putting a period at the end of a sentence, it signals to the parser that the thought is complete.

是包含复合语句块并且本质上终止的标记。这就像在一个句子的末尾加上一个句号,它向解析器发出信号,表示这个想法已经完成。

While being completely ugly it is valid to wrap every statement in {} and omit the ;

虽然完全丑陋,但将每个语句包装在 {} 中并省略 ; 是有效的。