为什么使用“do while"?环形? [英] Why use a "do while" loop?

查看:24
本文介绍了为什么使用“do while"?环形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直不明白为什么使用 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).

这篇关于为什么使用“do while"?环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆