简体   繁体   English

有人能解释一下 javaScript 中的“空”语句和普通分号有什么区别吗

[英]Can someone explain me what is the difference between an “empty” statement and a normal semicolon in javaScript

Can anyone explain me what is the difference between a normal semicolon;谁能解释一下普通分号有什么区别? that comes after every statement and the empty statement;它出现在每个语句和空语句之后; in javaScriptjavaScript

console.log(1);/* semicolon */ console.log(2)

and the empty statement that sometimes comes as the body of if, for, while, do-while statements in javaScript eg:以及有时作为javaScriptif、for、while、do-while语句的主体出现的空语句,例如:

if (true)
 ; /* empty statement */

is there a difference between both a semicolon;两个分号有区别吗? and an empty statement;和一个空的声明;

Each javascript statement should (although not all must) end with a semicolon, 'empty statement' also.每个 javascript 语句都应该(尽管不是全部必须)以分号结尾,“空语句”也是。 A semicolon in an empty statement is just a semicolon that completes the statement.空语句中的分号只是完成语句的分号。

For the final explanation: 'empty statement' is an statement without any sign hence its name.最后的解释:“空语句”是没有任何符号的语句,因此得名。 It must contain a terminating semicolon or the JS parser would not be able to distinguish it from other whitespace characters.它必须包含一个终止分号,否则 JS 解析器将无法将它与其他空白字符区分开来。 Thus, the semicolon sign;因此,分号; It is not an statement but is a mandatory semicolon ending the empty statement.它不是一个语句,而是一个强制分号结束空语句。

In JavaScript semicolons indicates the end of a statement.在 JavaScript 中,分号表示语句的结束。 A semicolon is not necessary after a statement if it is written on its own line, although it is considered good practice to do so.如果将分号写在单独的行上,则不需要在语句之后使用分号,尽管这样做被认为是一种好的做法。 But if more than one statement on a line is desired, then they must be separated by semicolons.但是,如果需要在一行中使用多个语句,则它们必须用分号分隔。

//these are ok
console.log(1)
console.log(2);

//this won't run
console.log(1) console.log(2) console.log(3)

//this will run
console.log(1); console.log(2); console.log(3);

An empty statement is used to provide no statement in circumstances where the JavaScript syntax would expect one.在 JavaScript 语法需要一个的情况下,空语句用于不提供任何语句。 For example in a for loop:例如在 for 循环中:

for (let i = 0; i < 10; array[i++] = 0)
; //JavaScript requires a statement here so do nothing

Also some JavaScript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (ASI).此外,一些 JavaScript 语句必须以分号结尾,因此会受到自动分号插入 (ASI) 的影响。 If you wish to deepen more into this I recommend you check this doc and this on MDN.如果你想更深入地了解这个,我建议你在 MDN 上查看这个文档这个 For a better understanding you may check the ECMAScript standard .为了更好地理解,您可以查看ECMAScript 标准

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM