为什么for循环和while循环会产生不同的结果,尽管它们的值相同?顺便说一句,我正在使用Javascript



我的新手对for循环和while循环之间的区别的理解是,它们在格式上不同,当我们知道要完成的确切迭代次数时,我们使用for循环,而当我们知道必须满足什么条件才能停止时,我们用while循环。也就是说,有人能解释以下代码的结果差异吗?

let countDown = 2;
while(countDown>1){
countDown--;
console.log(countDown)    
}
1
for(let countDown = 2; countDown>1; countDown--){
console.log(countDown)
}
2

正如U.Windl所评论的,for只是";句法糖";对于CCD_ 2循环。对于forwhile循环,程序的输出各不相同,因为在while循环中,countDown先递减,然后记录,而在for循环中,则countDown先记录,然后递减。while循环中的以下变化将使两者的输出相同,并等效于for循环。

let countDown = 2;
while(countDown>1){
console.log(countDown)   
countDown--; 
}

让我们看看forwhile循环说的是JavaScript For loop

The For Loop
The for loop has the following syntax:
for (statement 1; statement 2 (condition); statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
While Loop
while (condition) {
// code block to be executed
}

for中的程序中,循环Statement 3(即countDown--(是在代码块(即console.log(执行后执行的,这就是输出为2的原因。

while循环中,我们必须注意何时执行Statement 3(即,在这种情况下为倒计数(,而在for循环中,Statement 3总是在执行code block之后执行

for等效于while

for (; condition; ) {
// code block to be executed
}

while0等效于for

Statement 1
while (Statement 2) {
// code block to be executed
Statement 3
}

最新更新