for loop with a single semicolon throws the error "Uncaught SyntaxError: Unexpected token ')"

for loop with a single semicolon throws the error "Uncaught SyntaxError: Unexpected token ')"

下面的 for 循环工作正常

for (let count = 0;; count++) {
  console.log(count);
  if (count >= 3)
    break
}

只有一个分号 ; 而不是两个

时会抛出错误

for (let count = 0; count++) {
  console.log(count)
  if (count >= 3)
    break
}

Uncaught SyntaxError: Unexpected token ')

这就是 for 循环语法的工作原理。 for 循环中的分号将三个不同的表达式彼此分开——“变量初始化”语句、“停止条件”表达式和“post-迭代”表达式(我只是在这里编造名字,但他们符合他们的目的)。

所以,在这行代码中:

for (let count = 0;; count++)

通过在此处放置两个分号,您基本上是在说没有中间表达式,即此 for 循环没有停止条件。您可以省略任何您喜欢的部分。 for (;;) 也是一个有效的循环,并且与 while (true) 做同样的事情。重要的是,这两个分号在循环中总是

例如,如果您编写了这行代码:

for (let count = 0; count++)

您只提供了三个必需表达式中的两个。你提供哪两个? count++ 是停止条件吗?还是每次迭代后的操作?编译器不会猜测您的意图,它只是抛出一个语法错误,并要求您使用两个分号来明确表示您的意图是将其解释为 for (let count = 0;; count++),而不是 for (let count = 0; count++;)

在 MDN here.

上了解有关此 c 风格 for 循环的更多信息