6.6 while
Just
as the if statement is the basic control statement
that allows JavaScript to make decisions, the
while statement is the basic statement that allows
JavaScript to perform repetitive actions. It has the following
syntax:
while (expression)
statement
The while statement works by first evaluating
expression. If it is
false, JavaScript moves on to the next statement
in the program. If it is true, the
statement that forms the body of the loop
is executed and expression is evaluated
again. Again, if the value of expression
is false, JavaScript moves on to the next
statement in the program; otherwise, it executes
statement again. This cycle continues
until expression evaluates to
false, at which point the while
statement ends and JavaScript moves on. Note that you can create an
infinite loop with the syntax while(true).
Usually, you do
not want JavaScript to perform exactly the same operation over and
over again. In almost every loop, one or more variables change with
each iteration of the loop. Since the variables
change, the actions performed by executing
statement may differ each time through the
loop. Furthermore, if the changing variable or variables are involved
in expression, the value of the expression
may be different each time through the loop. This is
important -- otherwise, an expression that starts off
true would never change and the loop would never
end! Here is an example while loop:
var count = 0;
while (count < 10) {
document.write(count + "<br>");
count++;
}
As you can see, the variable
count
starts off at 0 in this example and is incremented each time the body
of the loop runs. Once the loop has executed 10 times, the expression
becomes false (i.e., the variable
count is no longer less than 10), the
while statement finishes, and JavaScript can move
on to the next statement in the program. Most loops have a counter
variable like count. The variable names
i, j, and k
are commonly used as a loop counters, though you should use more
descriptive names if it makes your code easier to understand.
•
Table of Contents
•
Index
•
Reviews
•
Examples
•
Reader Reviews
•
Errata
JavaScript: The Definitive Guide, 4th Edition
By
David Flanagan
Publisher
: O'Reilly
Pub Date
: November 2001
ISBN
: 0-596-00048-0
Pages
: 936
Slots
: 1
This fourth edition of the definitive reference to
JavaScript, a scripting language that can be embedded
directly in web pages, covers the latest version of the
language, JavaScript 1.5, as supported by Netscape 6 and
Internet Explorer 6. The book also provides complete
coverage of the W3C DOM standard (Level 1 and Level 2),
while retaining material on the legacy Level 0 DOM for
backward compatibility.