我的新手对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循环。对于for
和while
循环,程序的输出各不相同,因为在while循环中,countDown
先递减,然后记录,而在for
循环中,则countDown
先记录,然后递减。while循环中的以下变化将使两者的输出相同,并等效于for
循环。
let countDown = 2;
while(countDown>1){
console.log(countDown)
countDown--;
}
让我们看看for
和while
循环说的是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
}
while
0等效于for
Statement 1
while (Statement 2) {
// code block to be executed
Statement 3
}