问题
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