为什么即使条件为假,while循环仍然在运行?

huangapple go评论82阅读模式
英文:

Why is the while loop running even when the condition is false?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对JavaScript还很陌生,正在学习它的基础知识。我遇到了do...while循环,它解释说'do'命令会运行一次,然后检查条件。现在这是我的代码:

// 设置

const myArray = [];
let i = 10;


do {

}
while (i < 5) 
{
  myArray.push(i);
  i++;
}

console.log(myArray);

由于do中没有元素,它不应该在myArray中添加任何内容。然而,最终结果显示myArray中有10,我对此感到困惑。请帮助解答。

英文:

I am new to JavaScript and learning it's basics right now. I come accross do...while loop which explains that 'do' command will run once and then the condition would be checked. Now here is my code:
// Setup

const myArray = [];
let i = 10;


do {

}
while (i < 5) 
{
  myArray.push(i);
  i++;
}

console.log(myArray);

Since there is no element in the do, it shouldn't add anything in myArray. However, the end results shows 10 in myArray and I am confused why is it happening? Please assist.

答案1

得分: 5

更多关于blockdo while的信息。

const myArray = [];
let i = 10;

// 这是一个do while循环
do {

}
while (i < 5) 


// 这是与循环无关的一个代码块
{
  myArray.push(i);
  i++;
}

console.log(myArray);
英文:

More about block and do while

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const myArray = [];
let i = 10;

// this is a do while loop
do {

}
while (i &lt; 5) 


// this is a block unrelated to the loop
{
  myArray.push(i);
  i++;
}

console.log(myArray);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月27日 16:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定