【JavaScript 教程】第四章 程序流程04— while 循環(huán)語句

英文 | https://www.javascripttutorial.net/
譯文 | 楊小愛
那么,在今天的教程中,我們將一起來學(xué)習(xí)如何使用 JavaScript while 語句創(chuàng)建循環(huán)。
JavaScript while 循環(huán)語句簡介
while (expression) {// statement}
while 語句在每次循環(huán)迭代之前計算表達式。
如果表達式的計算結(jié)果為真,while 語句將執(zhí)行該語句。如果表達式的計算結(jié)果為 false,則繼續(xù)執(zhí)行 while 循環(huán)之后的語句。
while 循環(huán)在每次迭代之前計算表達式,因此,while 循環(huán)稱為預(yù)測試循環(huán)。由于這個原因,while 循環(huán)中的語句可能永遠不會被執(zhí)行。
以下流程圖說明了 while 循環(huán)語句:

請注意,如果要執(zhí)行該語句至少一次,并在每次迭代后檢查條件,則應(yīng)使用do-while語句。
JavaScript while 循環(huán)示例
請參閱以下使用該while語句的示例:
let count = 1;while (count < 10) {console.log(count);count +=2;}
它的工作原理
首先,在循環(huán)之外,計數(shù)變量設(shè)置為 1。
其次,在第一次迭代開始之前,while 語句會檢查 count 是否小于 10 并執(zhí)行循環(huán)體內(nèi)的語句。
第三,在每次迭代中,循環(huán)將 count 增加 2,在 5 次迭代后,條件 count < 10 不再為true,因此循環(huán)終止。
控制臺窗口中的腳本輸出如下:
13579
以下示例使用while循環(huán)語句將 0 到 10 之間的 5 個隨機數(shù)添加到數(shù)組中:
// create an array of five random number between 1 and 10let rands = [];let count = 0;const size = 5;while(count < size) {rands.push(Math.round(Math.random() * 10));count++;console.log('The current size of the array is ' + count);}console.log(rands);
The current size of the array is 1The current size of the array is 2The current size of the array is 3The current size of the array is 4The current size of the array is 5[]
在這個例子中:
首先,聲明并初始化一個數(shù)組。
其次,在 while 語句內(nèi)的每次循環(huán)迭代中添加一個 0 到 10 之間的隨機數(shù)。如果計數(shù)值等于大小變量的值,則循環(huán)停止。
總結(jié)
通過本教程的學(xué)習(xí),我們知道了如何使用 JavaScript 的 while 語句創(chuàng)建一個預(yù)測試循環(huán),只要條件為真,該循環(huán)就會執(zhí)行代碼塊。
學(xué)習(xí)更多技能
請點擊下方公眾號
![]()

