In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]

我与影子孤独终老i 提交于 2019-12-17 16:57:11

问题


When running following code on console:

var counter=0; while(counter<5){ console.log(counter); counter++; }

console o\p: 0 1 2 3 4 4

whereas for following code works fine, without repeating last value:

for(var i=0; i<5; i++){ console.log(i); }

console o\p: 0 1 2 3 4

Now, if I place above for loop after above mentioned while loop , output is perfectly fine:

var counter=0; while(counter<5){ console.log(counter); counter++; } for(var i=0; i<5; i++){ console.log(i); }

console o\p: 0 1 2 3 4 0 1 2 3 4

whereas, if I place while loop after for loop , repetition of last number found.

for(var i=0; i<5; i++){ console.log(i); } var counter=0;while(counter<5){ console.log(counter); counter++; }

console o\p: 0 1 2 3 4 0 1 2 3 4 4

Request all to provide a reason on this unexpected behavior of while loop. Thanks.


回答1:


When performing operations in the console, the return value of the last executed line is always output.

That means that simply writing

var counter = 0; ++counter;

will log 1 to the console.

The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression.




回答2:


The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself.

Try: var counter=0; while(counter<5){ console.log(counter++); }



来源:https://stackoverflow.com/questions/31434942/in-javascript-while-loop-repeats-last-number-when-counting-from-1-to-5-when-run

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