This question already has answers here:
Javascript while loop return value
(3个答案)
In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]
(2个答案)
去年关闭。
我在Google Chrome控制台中尝试了以下代码,并获得了此输出。为什么还要再打印4张?
输出:
编辑感谢@ggorlen指出这一点,它是block(
将返回值为5
(3个答案)
In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]
(2个答案)
去年关闭。
我在Google Chrome控制台中尝试了以下代码,并获得了此输出。为什么还要再打印4张?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
输出:
0
1
2
3
4
4
最佳答案
最后没有多余的4。您的循环是正确的,并且工作正常:)。那是i++
表达式的返回值,您在开发人员控制台中误认为console.log
。试试看,您会发现的;
var i=0;do{console.log('i = ', i);i++;}while(i<5);
编辑感谢@ggorlen指出这一点,它是block(
{}
)中最后一个表达式的返回值,它是i++
,i
递增该值并返回它的最后一个值(如果i = 4; i++
返回4并得出i = 5的值),(++i
,返回5并得出i = 5的值)var i=0;do{console.log('i = ', i);++i;}while(i<5);
将返回值为5