当条件是错误的时候,为什么这要进行循环升级?
我有以下循环:
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
...
据我所知,如果条件是错误的,则不应发生增量操作。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
循环的
的语法是:(
引用 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:(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'sfinal-expression
is performing the increment, thus settingi
to 2 before repeating the statement block.因此,我从戴夫(Dave)的回答中了解的是,for循环中发生的事情是:
而不是:
So what I understand from Dave's answer is that what happens inside the for loop is:
and not: