HTML and CSS Reference
In-Depth Information
EXAMPLE
6.7
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>For Loop</h2>
<font size="+2">
<script type="text/javascript">
1
for( var i = 0; i < 10; i++ ){
2
document.write(i);
3
}
</script>
</font>
</body>
</html>
EXPLANATION
1
The
for
loop is entered. The expression starts with step 1, the initialization of the
variable
i
to
0
. This is the only time this step is executed. The second expression,
step 2, tests to see if
i
is less than
10
, and if it is, the statements after the opening
curly brace are executed. When all statements in the block have been executed
and the closing curly brace is reached, control goes back into the
for
expression
to the last expression of the three.
i
is now incremented by one and the expression
in step 2 is retested. If true, the block of statements is entered and executed.
2
The value of
i
is displayed in the browser window (see Figure 6.6).
3
The closing curly brace marks the end of the
for
loop.
Figure 6.6
Output from Example 6.7.
The
for/in
loop is like the
for
loop, except it is used with JavaScript objects. Instead of
iterating the statements based on a looping condition, it operates on the properties of an
object. This loop is discussed in Chapter 9, “JavaScript Core Objects,” and is only men-
tioned here in passing, because it falls into the category of looping constructs.