HTML and CSS Reference
In-Depth Information
Putting all of these expressions together, you get the following
for
loop:
for (var i = 0; i < 4; i++) {
commands
}
The collection of commands that is run each time through a loop is collectively known
as a
command block
, a feature you've already worked with in functions. A command
block is indicated by its opening and closing curly braces { }. The following is an
example of a
for
loop that writes the value of the counter variable to a table cell on
the Web page:
for (var i = 0; i < 4; i++) {
document.write(“<td>” + i + “</td>”);
}
As shown in Figure 12-12, each time through the loop, the value displayed in the table
cell is changed by 1.
Figure 12-12
viewing a for loop
continue
if true
starting value
of the counter
variable
update after
each loop
Counter Values
Code Written
to the Page
0
<td>
0
</td>
<td>
1
</td>
<td>
2
</td>
<td>
3
</td>
1
2
3
One
for
loop can be nested within another. Figure 12-13 shows the code used to
create a table with three rows and two columns. This example uses two counter variables
named
rowNum
and
colNum
. The
rowNum
variable loops through the values 1, 2, and
3; and for each of those values, the
colNum
variable loops through the values 1 and 2.
Each time the value of the
colNum
variable changes, a new cell is added to the table.
Each time the value of the
rowNum
variable changes, a new row is added to the table.