Javascript continue statement in while loop causes an infinite loop

ぐ巨炮叔叔 提交于 2020-02-03 16:24:08

问题


I'm trying to create a while loop with a continue statement. However it seems to be causing an infinite loop and I can't figure out why.

The code below to me seems like it should start with the var tasksToDo at 3 then decrement down to 0 skipping number 2 on the way.

var tasksToDo = 3
while (tasksToDo > 0) {
    if (tasksToDo == 2) {
        continue;
    }
    console.log('there are ' + tasksToDo + ' tasks');
    tasksToDo--;
}

回答1:


conitnue, will go back to the while loop. and tasksToDo will never get decremented further than 2.

var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
 tasksToDo--;             // Should be here too.
 continue;
}

console.log('there are ' + tasksToDo + ' tasks');
tasksToDo--;
}



回答2:


continue causes the loop to skip the decrement and begin all over again. Once tasksToDo hits 2, it stays 2 forever.




回答3:


continue makes you go back to the beginning of the loop. You probably wanted to use break instead.

Or maybe make your decrement before the if block.




回答4:


It's not very clear what you're doing but from what I understand, you're trying to avoid executing logic inside while for tasksToDo = 2

var tasksToDo = 3
while (tasksToDo > 0) {
    if (tasksToDo != 2) {
        console.log('there are ' + tasksToDo + ' tasks');
    }
    tasksToDo--;
}

It wouldn't make sense to add a break in case tasksToDo = 2 since it would be easier to add that condition to the while (tasksToDo > 2).

Code here might be totally different to your real code though so I could be missing something.




回答5:


you are using continue; that continue your loop forever use break; to exit instead of continue;




回答6:


Should it be like this?

var tasksToDo = 3
while (tasksToDo > 0) {
if (tasksToDo == 2) {
 continue;
 console.log('there are ' + tasksToDo + ' tasks');
 }
tasksToDo--;
}



回答7:


The "continue;" statement prevent the execution of all remaining declarations in the code block.

Therefore the "tasksDo--" decrement is not executed after the loop reaches "i == 2" any more.

This creates an infinite loop!

use the "for" loop instead

the "for" loop solution for this case

var tasksToDo;

for (tasksToDo = 3; tasksToDo > 0; tasksToDo--){
    if (tasksToDo == 2) { continue; }
    console.log('there are ' + tasksToDo + ' tasks');
}

(the for loop accepts the decrement as its 3rd statement!)



来源:https://stackoverflow.com/questions/18403444/javascript-continue-statement-in-while-loop-causes-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!