Assignment020
For Loops
Another useful programming structure is the loop. JavaScript provides several ways to repeat commands easily. Let's start with the for loop. The following html was written with JavaScript:
This is loop item 1
This is loop item 2
This is loop item 3
This is loop item 4
This is loop item 5
This is loop item 6
This is loop item 7
This is loop item 8
This is loop item 9
This is loop item 10
- The for loop requires three parameters:
The first parameter is the initial setting for the loop variable. In this case we initialize a variable (i) and set i to 1.
- The second parameter is the condition, which must remain true to keep the loop running. In this case, the condition is "as long as i is less than or equal to 10."
- The third parameter is the increment expression which is often used to increment the variable. In this case we add 1 to i at each iteration of the loop.
<script language="Javascript" type="text/javascript">
for (var i=1; i<=10; i=i+1)
{
document.write("<strong>This is loop item " + i + "</strong><br />");
}
</script>
A shortcut method of writing the above is as follows:
<script language="javascript" type="text/javascript">
for (i=1; i<=10; i++)
{
document.write("<strong>This is loop item " + i + "</strong><br />");
}
</script>
The same three parameters are used, but with abbreviated coding. i=1 initializes the starting variable, and i++ adds 1 to the variable each time the loop runs (iteration).