问题描述
我从不明白为什么需要使用 do while 循环.我了解它们的作用,即执行while循环中包含的代码,而不先检查条件是否为真.
I've never understood why using a do while loops is necessary. I understand what they do, Which is to execute the code that the while loop contains without checking if the condition is true first.
但不是以下代码:
do{
document.write("ok");
}
while(x == "10");
与以下内容完全相同:
document.write("ok");
while(x == "10"){
document.write("ok");
}
也许我很愚蠢,缺少明显的东西,但是我没有看到在上面的示例中使用 do while 的好处.
Maybe I'm being very stupid and missing something obvious out but I don't see the benefit of using do while over my above example.
推荐答案
您的示例代码有误:
do{
document.write("ok");
}while(x == "10"){
document.write("ok");
}
这将是实际的形式:
do {
document.write("ok");
} while(x == "10");
您是正确的,它在检查条件之前执行了内部代码块,但是它不需要按照您拥有它的方式来复制内部代码块. do/while构造(正如您已经说过的)是一种确保一段代码执行1次或多次而不是0次或多次(取决于条件)的方法.
You are correct that it executes the inner code block before checking the condition, but it doesn't need to duplicate the inner code block the way you have it. The do/while construct is (as you've already stated) a way to make sure that a piece of code is executed 1 or more times instead of 0 or more times (depending on the conditional).
这篇关于为什么要使用“做一会儿"环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!