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;
}