Udostępnij za pośrednictwem


for Loops

The for statement specifies a counter variable, a test condition, and an action that updates the counter. Before each iteration of the loop, the condition is tested. If the test is successful, the code inside the loop is executed. If the test is unsuccessful, the code inside the loop is not executed, and the program continues on the first line of code immediately following the loop. After the loop is executed, the counter variable is updated before the next iteration begins.

Using for Loops

If the condition for looping is never met, the loop is never executed. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so be cautious when writing your loop conditions. In this example, the for loop is used to initialize the elements of an array with the sum of the previous elements.

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

The output of this program is:

0: 0
1: 1
2: 3
3: 6
4: 10
5: 15
6: 21
7: 28
8: 36
9: 45

There are two loops in the next example. The code block of the first loop is never executed, while the second loop is an infinite loop.

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

See Also

Reference

for Statement

Other Resources

Loops in JScript

JScript Conditional Structures

JScript Reference