根据MDN,do while loop
指出这是语法,即使出现这种情况,它也会运行一次
做 声明 while(条件);
以下是我的代码
let mergeArr3 = (arr1 , arr2) => {
let i = 1;
do {
console.log('hello') //prints hello 5 times
i++;
}
while (i < 6 ) {
console.log(i) //prints 6
console.log('world') // prints world once
}
}
mergeArr3(arr1 , arr2)
我正在努力理解两件事:
为什么当6 <6假设被评估为false时console.log(i)
打印6
并且当i === 6时不应运行该行代码。
Do
应该运行一次,但是为什么要运行5次?
答案 0 :(得分:3)
“循环”部分只是do
和while
之间的块。
它至少执行一次,并且直到while条件为falsy
在while之后编写的代码块只是一个独立的代码块,为了更好的理解,应该这样阅读:
let i = 1;
// loop do -- while
do {
console.log('hello') //prints hello 5 times
i++;
}
while (i < 6) // if the condition here is true, execute the above block again.
// this is just a legal block of code but completely unrelated to the loop.
{
console.log(i) //prints 6
console.log('world') // prints world once
}
因此,当i 不小于6时,即i刚好为6时,将执行循环后的最后一个块。
答案 1 :(得分:0)
while (i < 6 )
{
console.log(i) //prints 6
console.log('world') // prints world once
}
while条件之后的部分绝不是do的一部分,而它只是带有控制台的普通块。始终会像下面这样由JS或任何支持do-while的语言进行解释:
let mergeArr3 = (arr1 , arr2) => {
let i = 1;
do {
console.log('hello') //prints hello 5 times
i++;
}
while (i < 6 );
{
console.log(i) //prints 6
console.log('world') // prints world once
}
}