for 迴圈
for 陳述式會指定計數器變數、測試條件和更新計數器的動作。 在每次迴圈重複前,會先測試條件。 如果測試成功,會執行迴圈內部的程式碼。 如果測試不成功,就不會執行迴圈內部的程式碼,而且程式會立即執行緊接在迴圈之後的第一行程式碼。 迴圈執行過後,會下個重複項目開始之前更新計數器變數。
使用 for 迴圈
如果迴圈處理的條件從來都沒有符合過,就永遠不會執行迴圈。 如果一直符合測試條件,便會造成無限迴圈。 雖然在某些情況下可能希望得到前面的結果,但極少人會希望得到後面的結果,所以在撰寫迴圈條件時要十分謹慎。 在本範例中,for 迴圈是以前一元素之總和來初始化陣列元素。
var sum = new Array(10); // Creates an array with 10 elements
sum[0] = 0; // Define the first element of the array.
var iCount;
// Counts from 0 through one less than the array length.
for(iCount = 0; iCount < sum.length; iCount++) {
// Skip the assignment if iCount is 0, which avoids
// the error of reading the -1 element of the array.
if(iCount!=0)
// Add the iCount to the previous array element,
// and assign to the current array element.
sum[iCount] = sum[iCount-1] + iCount;
// Print the current array element.
print(iCount + ": " + sum[iCount]);
}
本程式的輸出為:
0: 0
1: 1
2: 3
3: 6
4: 10
5: 15
6: 21
7: 28
8: 36
9: 45
下一個範例中有兩個迴圈。 第一個迴圈的程式碼區塊永遠不會執行到,而第二個迴圈是一個無限迴圈。
var iCount;
var sum = 0;
for(iCount = 0; iCount > 10; iCount++) {
// The code in this block is never executed, since iCount is
// initially less than 10, but the condition checks if iCount
// is greater than 10.
sum += iCount;
}
// This is an infinite loop, since iCount is always greater than 0.
for(iCount = 0; iCount >= 0; iCount++) {
sum += iCount;
}