在 JavaScript 裏迴圈是用來重覆執行一定次數的程式碼或在某些特定的條件成立時。
範例
For 迴圈
如何寫一個 for 迴圈。使用 For 迴圈來執行同樣的程式碼特定的次數。
透過 HTML 標題
以不同的 HTML 標題為例子的For迴圈。
While 迴圈
當設定的條件為真時,使用while 迴圈執行同樣的程式碼。
Do while 迴圈
當設定的條件為真時以 do...while 迴圈來執行同樣的程式碼。即使條件不成立,此種迴圈還是會執行一次,因為在條件被測試之前此類的迴圈敘述即已被執行。
JavaScript 迴圈
在撰寫程式碼時經常的使用到,你要同樣的程式碼一次又一次執行. 只要在script增加幾行程式,我們就可以使用迴圈來完成一個工作,如下:
JavaScript 有二種不同的迴圈:
- for - 執行同樣的程式碼指定的次數。
- while - 當特定的條件成立時,執行同樣的程式碼。
for 迴圈
for 迴圈是用在當你已經知道script 要執行幾次。
語法
for (var=變數啟始值;var
{
執行的程式碼
}
|
範例
說明: 下列的例子定義一個迴圈,它的啟始值是 0 i=0. 只要 i
是小於或等於10,迴圈會不斷的執行,並且每執行迴圈一次 i 的值會自動的加1。
註: 逐次增加的參數也可以是負值,且
也可以是任何的比較敘述。
執行結果
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
|
while 迴圈
while 迴圈是用來當某些特定的條件成立時,你要迴圈持續的執行。l
註:" "也可以是任何的比較敘述。
範例
說明: 以下的例子定義一個迴圈,它的啟始值是0 i=0. 只要變數 i小於等於10,迴圈會持續的執行,在每執行一次迴圈後,變數
i 會自動的加1。
執行結果
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
|
do...while 迴圈
do...while 迴圈是不同的 while 迴圈。
此類迴圈總是會執行區塊內的程式碼一次,只要特定的條件為真,它會持續的執行。即使條件不成立迴圈也會執行一次,因為程式碼是在條件測試前就已執行。
範例
執行結果
|