在JavaScript中使用While循环和Do...While循环
介绍
自动化是使系统自动运行的技术; 在编程中,我们使用 loops 来自动执行重复的任务。 循环是编程语言最有用的特性之一,在本文中,我们将了解 JavaScript 中的 while 和 do...while 循环。
JavaScript 中的 while 和 do...while 语句类似于 条件语句 ,它们是在指定条件导致 true 时执行的代码块. 与只计算一次的 if 语句不同,循环将运行多次,直到条件不再计算为 true。
您将遇到的另一种常见循环类型是 for 语句 ,它执行一定次数。 while 和 do...while 循环是基于条件的,因此无需事先知道循环将运行多少次。
While 循环
在 JavaScript 中,while 语句是一个循环,只要指定条件的计算结果为 true,就会执行。
语法与 if 语句非常相似,如下所示。
while (condition) {
// execute code as long as condition is true
}
while 语句是 JavaScript 中最基本的循环。
例如,假设我们有一个有人口限制的水族馆。 对于循环的每次迭代,我们将添加一条鱼。 一旦水族馆有 10 条鱼,将达到种群限制,程序将停止添加更多鱼。
水族馆.js
// Set population limit of aquarium to 10
const popLimit = 10;
// Start off with 0 fish
let fish = 0;
// Initiate while loop to run until fish reaches population limit
while (fish < popLimit) {
// add one fish for each iteration
fish++;
console.log("There's room for " + (popLimit - fish) + " more fish.");
}
运行上述程序后,我们将收到以下输出,显示程序通过 while 循环的迭代,直到条件不再被评估为 true。
OutputThere's room for 9 more fish. There's room for 8 more fish. There's room for 7 more fish. There's room for 6 more fish. There's room for 5 more fish. There's room for 4 more fish. There's room for 3 more fish. There's room for 2 more fish. There's room for 1 more fish. There's room for 0 more fish.
在我们的示例中,我们将 while 循环设置为运行,只要鱼的数量少于水族馆的种群限制。 对于每次迭代,将一条鱼添加到水族箱中,直到所有 10 点都被填满。 此时,循环停止运行。
无限循环
顾名思义, 无限循环 是一个将永远运行的循环。 如果您不小心进行了无限循环,可能会导致您的浏览器或计算机崩溃。 了解无限循环很重要,这样您就可以避免它们。
当 while 语句的条件设置为 true 时,会发生常见的无限循环。 下面是一个将永远运行的代码示例。 没有必要测试任何无限循环。
无限循环.js
// Initiate an infinite loop
while (true) {
// execute code forever
}
无限循环将永远运行,但可以使用 break 关键字终止程序。
在下面的示例中,我们将 if 语句添加到 while 循环中,当满足该条件时,我们将使用 break 终止循环。
北极熊.js
// Set a condition to true
const iceCapsAreMelting = true;
let polarBears = 5;
// Initiate infinite loop
while (iceCapsAreMelting) {
console.log(`There are ${polarBears} polar bears.`);
polarBears--;
// Terminate infinite loop when following condition is true
if (polarBears === 0) {
console.log("There are no polar bears left.");
break;
}
}
当我们运行上面的代码时,输出将如下所示。
OutputThere are 5 polar bears. There are 4 polar bears. There are 3 polar bears. There are 2 polar bears. There are 1 polar bears. There are no polar bears left.
请注意,这不一定是创建和终止循环的实用方法,但 break 是一个需要注意的有用关键字。
做…While循环
我们已经了解了 while 循环,只要指定条件为真,它就会执行一段代码。 基于此的是 do...while 语句,它与 while 非常相似,主要区别在于 do...while 循环将始终执行一次,即使条件永远不会为真.
下面我们将演示 do...while 循环的语法。
do {
// execute code
} while (condition);
如您所见,循环的 do 部分首先出现,然后是 while (condition)。 代码块将运行,然后将在正常的 while 循环中测试条件。
为了测试这一点,我们可以将一个变量设置为 0,在 do 语句中将其递增,并将我们的条件设置为 false。
falseCondition.js
// Set variable to 0
let x = 0;
do {
// Increment variable by 1
x++;
console.log(x);
} while (false);
Output1
我们的输出输出到 1,这意味着代码块在被不成功的 while 条件停止之前迭代了一次循环(来自 0)。
请记住,循环将至少迭代一次,do...while 循环可用于与 while 循环相同的目的。
结论
在本教程中,我们了解了 JavaScript 中的 while 循环、do...while 循环和无限循环。
重复性任务的自动化是编程中极其重要的一部分,这些循环可以帮助您的程序更加高效和简洁。
要了解更多信息,请阅读 Mozilla Developer Network 上的 while 和 do...while 循环。