我希望这段代码最多只能打印 10 个。但它最多可以打印 12 个。我可以修改代码来检查 i<10 instead of i<=10. But I do not understand why the while loop goes on to print 12. I know my logic is correct.
我希望下面的代码最多打印 10 个。但它最多打印 12 个。
let i=0;
while (i<=10){
console.log(i);
i+=2;
}
代码按预期工作。它不打印 12。 使用代码片段可以让您轻松验证代码。
let i=0;
while (i<=10){
console.log(i);
i+=2;
}
它最多打印 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) {
i += 2;
if (i > 10) {
break;
}
}