当条件是错误的时候,为什么这要进行循环升级?

发布于 2025-02-07 21:30:07 字数 420 浏览 2 评论 0 原文

我有以下循环:

for (let i = 100; i > 1; i++) {
    console.log(i);
    i = 1;
}

当我再次进入for循环时,它是1,所以条件i> 1是错误的,但它一直无限地循环并打印2。

我也尝试使用i!== 1和/或++ i,但同样的事情也发生了。

其他语言中的相同行为:

for (int i = 100; i > 1; i++) {
    std::cout << i << std::endl;
    i = 1;
}

输出:

...
2
2
2
...

据我所知,如果条件是错误的,则不应发生增量操作。

I have the following loop:

for (let i = 100; i > 1; i++) {
    console.log(i);
    i = 1;
}

When i enters the for loop again it is 1 so the condition i > 1 is false but it keeps looping infinitely and printing 2.

I also tried with i !== 1 and/or ++i but the same thing happens.

Same behaviour in other languages:

for (int i = 100; i > 1; i++) {
    std::cout << i << std::endl;
    i = 1;
}

Output:

...
2
2
2
...

As far as I know the increment operation should not happen if the condition is false.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情栀口红 2025-02-14 21:30:07

循环的的语法是:(

for ([initialization]; [condition]; [final-expression])
   statement

引用 https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/statement/statements/for ), final-expression

在每个循环迭代的末端进行评估的表达式。这是在之前发生的下一个条件评估。通常用于更新或增加计数器变量。

您的语句块以设置 i 到1。 输入下一个迭代之前,循环的 final-expression 正在执行增量,因此在重复语句块之前将 i 设置为2。

The syntax of a for loop is:

for ([initialization]; [condition]; [final-expression])
   statement

(quotting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for), the final-expression is:

"An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable."

Your statement block ends with setting i to 1. Before entering the next iteration, the loop's final-expression is performing the increment, thus setting i to 2 before repeating the statement block.

嘿咻 2025-02-14 21:30:07

因此,我从戴夫(Dave)的回答中了解的是,for循环中发生的事情是:

for (let i = 100; i > 1;) {
    console.log(i);
    i = 1;
    i++;
}

而不是:

for (let i = 100; i > 1;) {
    i++;
    console.log(i);
    i = 1;
}

So what I understand from Dave's answer is that what happens inside the for loop is:

for (let i = 100; i > 1;) {
    console.log(i);
    i = 1;
    i++;
}

and not:

for (let i = 100; i > 1;) {
    i++;
    console.log(i);
    i = 1;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文