文章目錄
- JavaScript 有兩種不同種類的迴圈:
- 文法:
- 執行個體:
- 結果:
- 文法:
- 執行個體:
- 結果:
- 文法:
- 執行個體:
- 結果:
JavaScript 中的迴圈用來將同一段代碼執行指定的次數(或者當指定的條件為 true 時)。
執行個體
-
For 迴圈
-
如何編寫 loop 迴圈來按照指定的次數執行相同的代碼。
-
迴圈產生 HTML 標題
-
如何使用Loop迴圈來產生不同的HTML標題。
JavaScript 迴圈
在編寫代碼時,你常常希望反覆執行同一段代碼。我們可以使用迴圈來完成這個功能,這樣就用不著重複地寫若干行相同的代碼。
JavaScript 有兩種不同種類的迴圈:
-
for
-
將一段代碼迴圈執行指定的次數
-
while
-
當指定的條件為 true 時迴圈執行代碼
for 迴圈
在指令碼的運行次數已確定的情況下使用 for 迴圈。
文法:
for
(變數=開始值;變數<=結束值;變數=變數+步進值) { 需執行的代碼}
執行個體:
解釋:下面的例子定義了一個迴圈程式,這個程式中 i 的起始值為 0。每執行一次迴圈,i 的值就會累加一次 1,迴圈會一直運行下去,直到 i 等於 10 為止。
注釋:步進值可以為負。如果步進值為負,需要調整 for 聲明中的比較子。
<html><body><script type="text/javascript">var i=0for (i=0;i<=10;i++){document.write("The number is " + i)document.write("<br />")}
</script></body></html>
結果:
The number is 0The number is 1The number is 2The number is 3The number is 4The number is 5The number is 6The number is 7The number is 8The number is 9The number is 10
while 迴圈
JavaScript 中的迴圈用來將同一段代碼執行指定的次數(或者當指定的條件為 true 時)。
執行個體
-
While 迴圈
-
利用 while 迴圈在指定條件為 true 時來迴圈執行代碼。
-
Do while 迴圈
-
利用 do...while 迴圈在指定條件為 true 時來迴圈執行代碼。在即使條件為 false 時,這種迴圈也會至少執行一次。這是因為在條件被驗證前,這個語句就會執行。
while 迴圈
while 迴圈用於在指定條件為 true 時迴圈執行代碼。
文法:
while
(變數<=結束值){ 需執行的代碼}
注意:除了<=,還可以使用其他的比較子。
執行個體:
解釋:下面的例子定義了一個迴圈程式,這個迴圈程式的參數 i 的起始值為 0。該程式會反覆運行,直到 i 大於 10 為止。i 的步進值為 1。
<html><body><script type="text/javascript">var i=0while (i<=10){document.write("The number is " + i)document.write("<br />")i=i+1}
</script></body></html>
結果:
The number is 0The number is 1The number is 2The number is 3The number is 4The number is 5The number is 6The number is 7The number is 8The number is 9The number is 10
do...while 迴圈
do...while 迴圈是 while 迴圈的變種。該迴圈程式在初次運行時會首先執行一遍其中的代碼,然後當指定的條件為 true 時,它會繼續這個迴圈。所以可以這麼說,do...while 迴圈為執行至少一遍其中的代碼,即使條件為 false,因為其中的代碼執行後才會進行條件驗證。
文法:
do
{ 需執行的代碼}while
(變數<=結束值)
執行個體:
<html><body><script type="text/javascript">var i=0do {document.write("The number is " + i)document.write("<br />")i=i+1}while (i<0)
</script></body></html>
結果:
The number is 0