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
Why are semicolons not used after if/else statements?
提问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-else
must be followed by either a statement or a group of statements.
基本上, anif-else
后面必须跟一个语句或一组语句。
if-else
followed by a statement:
if-else
接着是一个声明:
if (condition) statement;
if (condition); // followed by a statement (an empty statement)
if-else
followed by group of statements:
if-else
接着是一组语句:
if (condition) {
statement;
statement;
}
if (condition) {
// followed by a group of statements of zero length
}
if-else
must end with a ;
if it is followed by a single statement. if-else
does 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 ;
虽然完全丑陋,但将每个语句包装在 {} 中并省略 ; 是有效的。