[英]Why are semicolons not used after if/else statements?
我知道在 Javascript 中的所有语句之后使用分号是一种很好的语法,但是有人知道为什么 if/else 语句在大括号之后不需要它们吗?
{
and }
begin and close a group of statements {
和}
开始和关闭一组语句Basically, an if-else
must be followed by either a statement or a group of statements.基本上,
if-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-else
必须以 a 结尾;
if it is followed by a single statement.如果后面跟着一个语句。
if-else
does not end with a ;
if-else
不以 a 结尾;
when followed by a group of statements because ;
when 后面跟着一组语句,因为
;
is used to end a single statement, and is not used for ending a group of statements.用于结束单个语句,不用于结束一组语句。
The real answer is because many modern languages copied their syntax from C, which has this property.真正的答案是因为许多现代语言从 C 复制了它们的语法,C 具有此属性。 JavaScript is one of these languages.
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 single statement in the then- or else- clause, you'll need to terminate it with a semicolon.如果将单个语句放在 then- 或 else- 子句中,则需要用分号终止它。 Again, just as in C, with the extra JavaScript twist that ;
同样,就像在 C 中一样,额外的 JavaScript 扭曲是 ; is optional at the end of a line, if inserting it would not cause a syntax error.
在一行的末尾是可选的,如果插入它不会导致语法错误。
Because the curly braces themselves are termination characters.因为花括号本身就是终止符。
They 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 ;虽然完全丑陋,但将每个语句包装在 {} 中并省略 ; 是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.