JavaScript While 和 Do While 循环的区别及示例。虽然 Do While 循环和 While 循环看起来相似,但它们的执行方式不同。
- 在 While 循环中,条件在循环开始时进行测试。如果条件为 True,则执行循环内的语句。这意味着 While 循环仅在条件为 True 时才执行代码块。
- Do While 循环在循环结束时测试条件。因此,即使条件失败,Do While 也会至少执行代码块内的语句一次。
我认为当您看到示例时,您将完全理解它。所以,让我们用 While 循环和 Do While 循环编写相同的程序。
JavaScript While 循环示例
在此 JavaScript 程序中,我们声明一个整数,然后检查 One 是否大于 Ten。如果条件为 True,则应显示输出“X is Greater Than 10”。在 While 循环 外部还有一个语句,它将在 while 循环之后运行。
<!DOCTYPE html>
<html>
<head>
<title> Difference </title>
</head>
<body>
<h1> JavaScript While Loop </h1>
<script>
var x = 1;
while (x > 10)
{
document.write("<br\> <b> X Is greater Than 10 </b>");
}
document.write("<br\> <b> Statement Outside the while loop </b>");
</script>
</body>
</html>
JavaScript While Loop
Statement Outside the while loop
Do While 循环示例
我们将使用 Do While 编写相同的 JavaScript 示例。
<!DOCTYPE html>
<html>
<head>
<title> Difference </title>
</head>
<body>
<h1> JavaScript Do While Loop </h1>
<script>
var x = 1;
do
{
document.write("<br\> <b> X Is greater Than 10 </b>");
}while (x > 10);
document.write("<br\> <b> Statement Outside the while loop </b>");
</script>
</body>
</html>

尽管 Do while 循环条件失败,但循环内的语句仍然执行了一次。因为在执行完语句后,编译器才测试条件。
评论已关闭。