为什么这个`do`–`while`循环在结束之后重复最后一个值? [英] Why does this `do`–`while` loop repeat the last value after the end?
问题描述
我在Google Chrome控制台中尝试了以下代码,并获得了此输出.为什么还要再打印4张?
I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
输出:
0
1
2
3
4
4
推荐答案
最后没有多余的4个.您的循环是正确的,并且可以正常工作:).那是 i ++
表达式的返回值,您在开发人员控制台中误认为了 console.log
.试试这个,您会发现的;
There is no extra 4 at end. Your loop is correct and works just fine :). That's return value of the i++
expression, which you are mistaking for console.log
in developer console. Try this, you will figure it out;
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)
Edit Thanks to @ggorlen for pointing this out, it's the return value of last expression in block({}
) which is i++
, i
increments the value and returns it's last value (if i = 4; i++
returns 4 and makes value of i = 5), (++i
, returns 5 and makes value of i = 5)
var i=0;do{console.log('i = ', i);++i;}while(i<5);
将给出5的返回值
这篇关于为什么这个`do`–`while`循环在结束之后重复最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!