简体   繁体   English

为什么我将 for 循环代码转换为 while 循环代码失败了?

[英]Why my transformation of a for-loop code into a while-loop one failed?

In the process of playing with getting all the odd numbers from 30 to 40 in a javascript's while-loop, I have encountered the problem of not being able to equally transform my for-loop code, which solves this task, into its while-loop counterpart.在尝试在 javascript 的 while 循环中获取 30 到 40 的所有奇数的过程中,我遇到了无法将解决此任务的 for 循环代码平等地转换为它的 while 循环的问题对方。 My while-loop gives out an extra '41'.我的while循环给出了一个额外的'41'。 Was my transformation wrong or while-loop is essentially different from the for-loop in JavaScript?我的转换是错误的还是 while 循环与 JavaScript 中的 for 循环本质上不同?

const max = 40;
const min = 30;
for (let i = min + 1; i < max; i += 2) {
  console.log(i);
}
// 31 33 35 37 39


const max = 40;
const min = 30;
let i = min + 1;
while (i < max) {
  console.log(i);
  i += 2;
}
// 31 33 35 37 39 41

Yet, if we write down 'console.log('end')' beneath the above while-loop, it will be working correctly.然而,如果我们在上面的 while 循环下面写下 'console.log('end')',它就会正常工作。 How to explain this?这要怎么解释? Is it a bug in the system?是系统的bug吗?

I tried logging some more output at the end of while loop and it returns me the expected output but with that extra logged statement.我尝试在 while 循环结束时记录更多 output ,它返回给我预期的 output 但带有额外记录的语句。

var  min = 30, max = 40;
var i = min + 1;
while(i < max){
console.log(i);
i = i + 2;
}
console.log('end');

//31 33 35 37 39 end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM