Monday, May 11, 2009

Create a for Loop in JavaScript

JavaScript, like all programming languages, supports loops or repetition, in its case with the for statement. The for statement in JavaScript comes in two flavors: one loops over values, the other over entries in an object or array.

Loop Over Values in JavaScript
1. Code the for statement, following the syntax below:
for (variable=value; condition; increment) { statement(s) }

2. Loop over a range of values by setting a variable equal to the initial value, specifying for the condition the test that the variable not exceed the maximum value, and incrementing the variable each time through the loop. In the example below, the numbers between 1 and 9 will be displayed in a series of alert boxes. (i++ means to increment the value of the variable i by 1.)
for (i=1; i<10; i++) { alert (i); }

3. Terminate processing of the loop's statements and return to the top for the next iteration, if necessary, by using the continue statement.

4. Break out of the loop, continuing with the statement following it, by coding a break statement if necessary.

Loop Over Object or Array Elements

1. Code the for statement, following the syntax below. "in" is a special JavaScript keyword used for this purpose.
for (variable in object) { statement(s) }

2. Process each element in the object or array as appropriate. The variable given in the for statement will take on the value of each array index, or object field, in turn. Example:
for (i in my_array) { alert ("Value of element " + i + " is " + my_array[i]);

3. Move to the next iteration, or break out of the loop, using the same continue and break statements described in the preceding section.

No comments: