JavaScript while 循环打印偶数在条件为 false 后再次执行一次

问题描述 投票:0回答:1

我有一个简单的 while 循环来打印从 0 到 10 的偶数。我希望这段代码最多只打印 10。但它最多打印 12。我可以修改代码来检查 i<10 instead of i<=10. But I do not understand why the while loop goes on to print 12.

我希望下面的代码最多打印 10 个。但它最多打印 12 个。

let i=0;
while (i<=10){
    console.log(i);
    i+=2;
}
javascript loops while-loop
1个回答
0
投票

它最多打印 12,因为你设置了条件 i <= 10, i+=2. meaning as long as i is less than or equal to 10, it is going to add 2 to i. so if i is equal to 10, it is still going to add 2 to i. To achieve your desired result, i have update the code, see below:

let i = 0;
while (i <= 10) {
    console.log(i);
    i += 2;
    if (i > 10) {
        break;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.