介绍
自动化是使系统自动运行的技术;在编程中,我们使用 ** loop 来自动化重复任务。
JavaScript 中的虽然
和做...而
陈述类似于 条件陈述,这些代码块如果指定条件结果为 ‘true’就会执行。
您会遇到的另一种常见的循环类型是 for
语句,它执行了一定的次数。 'while' 和 'do...while' 循环是基于条件的,因此不需要事先知道循环会运行多少次。
走路时
在JavaScript中,一个while
陈述是执行的循环,只要指定条件被评估为true
。
语法非常类似于如下所示的如果
语句。
1while (condition) {
2 // execute code as long as condition is true
3}
而
语句是 JavaScript 中构建的最基本的循环。
举个例子,假设我们有一个有人口限制的水族馆. 对于循环的每一次迭代,我们将添加一个鱼. 一旦水族馆有10
鱼,将达到人口限制,该计划将停止添加更多的鱼。
1[label aquarium.js]
2
3// Set population limit of aquarium to 10
4const popLimit = 10;
5
6// Start off with 0 fish
7let fish = 0;
8
9// Initiate while loop to run until fish reaches population limit
10while (fish < popLimit) {
11 // add one fish for each iteration
12 fish++;
13 console.log("There's room for " + (popLimit - fish) + " more fish.");
14}
一旦我们运行上述程序,我们将收到以下输出,显示程序通过而
循环的迭代,直到条件不再被评估为真实
。
1[secondary_label Output]
2There's room for 9 more fish.
3There's room for 8 more fish.
4There's room for 7 more fish.
5There's room for 6 more fish.
6There's room for 5 more fish.
7There's room for 4 more fish.
8There's room for 3 more fish.
9There's room for 2 more fish.
10There's room for 1 more fish.
11There's room for 0 more fish.
在我们的例子中,我们将我们的同时
循环设置为运行,只要鱼的数量小于水族馆的人口限制. 对于每一次迭代,一个鱼被添加到水族馆,直到所有10
点都填满。
无限的路径
一个 无限循环,正如它的名字所暗示的那样,是一个循环,它将永远运行. 如果您意外创建一个无限循环,它可能会崩溃您的浏览器或计算机。
常见的无限循环发生在而
声明的条件设置为真
时。以下是永久运行代码的例子。
1[label infiniteLoop.js]
2
3// Initiate an infinite loop
4while (true) {
5 // execute code forever
6}
一个无限的循环将永远运行,但程序可以用破
关键字终止。
在下面的示例中,我们将添加一个如果
陈述到而
循环,当该条件满足时,我们将用破
结束循环。
1[label polarBears.js]
2
3// Set a condition to true
4const iceCapsAreMelting = true;
5let polarBears = 5;
6
7// Initiate infinite loop
8while (iceCapsAreMelting) {
9 console.log(`There are ${polarBears} polar bears.`);
10 polarBears--;
11 // Terminate infinite loop when following condition is true
12 if (polarBears === 0) {
13 console.log("There are no polar bears left.");
14 break;
15 }
16}
当我们运行上面的代码时,输出将如下。
1[secondary_label Output]
2There are 5 polar bears.
3There are 4 polar bears.
4There are 3 polar bears.
5There are 2 polar bears.
6There are 1 polar bears.
7There are no polar bears left.
请注意,这不一定是创建和终止循环的实际方法,但打破
是一个有用的关键字。
走路时...走路时
我们已经了解到而
循环,该循环执行一个代码块,只要指定条件是正确的。
下面我们将展示做...而
循环的语法。
1do {
2 // execute code
3} while (condition);
正如你所看到的,循环的做
部分首先出现,其次是虽然(条件)
。
为了测试这一点,我们可以将变量设置为0
,将其增加到做
语句中,并将我们的条件设置为假
。
1[label falseCondition.js]
2
3// Set variable to 0
4let x = 0;
5
6do {
7 // Increment variable by 1
8 x++;
9 console.log(x);
10} while (false);
1[secondary_label Output]
21
我们的输出出为1
,这意味着代码块通过循环重复一次(从0
开始),然后被一个失败的而
条件阻止。
虽然要记住,循环至少会重复一次,但做...而
循环可以用来与而
循环相同的目的。
结论
在本教程中,我们了解了JavaScript中的while
循环、do...while
循环和无限循环。
重复任务的自动化是编程的一个非常重要的部分,这些循环可以帮助使您的程序更高效和简洁。
要了解更多信息,请阅读 Mozilla 开发者网络上的 while
和 do...while
环节。