HTML and CSS Reference
In-Depth Information
In this loop, the
while
loop continues as long as the value of the
i
variable remains
less than 4. Each time through the command block, the loop writes the value of
i
into a
table cell and then increases the counter by 1.
Like
for
loops,
while
loops can be nested within one another. The following code
demonstrates how to create the 3 × 2 table shown earlier in Figure 12-13 using nested
while
loops:
var rowNum = 1;
while (rowNum < 4) {
document.write(“<tr>”);
var colNum = 1;
while (colNum < 3) {
document.write(“<td>” + rowNum + “,” + colNum + “</td>”);
colNum++;
}
document.write(“</tr>”);
rowNum++;
}
Again, the initial values of the counter variables are set before the
while
loops are run
and are updated within the command blocks.
Because
for
loops and
while
loops share many of the same characteristics, which
one you choose for a given application is often a matter of personal preference. In
general,
for
loops are used whenever you have a counter variable and
while
loops are
used for conditions that don't easily lend themselves to using counters. For example, you
could construct a
while
loop that would run only when the current time falls within a
specified time interval.
Use a
for
loop when your
loop contains a counter
variable. Use a
while
loop for a more general
stopping condition.
Exploring the
do
/
while
Loop
In the
for
and
while
loops, the test to determine whether to continue the loop is made
before the command block is run. JavaScript also supports a program loop called
do
/
while
that tests the condition to continue the loop right after the latest command block
is run. The structure of the
do
/
while
loop is as follows:
do {
commands
}
while (
continue
);
For example, the following code is used to create the table shown earlier in Figure 12-12
as a
do
/
while
loop:
var i = 0;
do {
document.write(“<td>” + i + “</td>”);
i++;
}
while (i < 4);
The
do
/
while
loop is usually used when the program loop should run at least once
before testing for the stopping condition.