英文:
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
const myArray = [];
let i = 10;
// 这是一个do while循环
do {
}
while (i < 5)
// 这是与循环无关的一个代码块
{
myArray.push(i);
i++;
}
console.log(myArray);
英文:
<!-- 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 < 5)
// this is a block unrelated to the loop
{
myArray.push(i);
i++;
}
console.log(myArray);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论