13.2. for
Statement
Like
a while loop, a for loop is executed repeatedly as long
as a condition is satisfied. If the number of times to be repeated is
certain, using the for statement will be more convenient than
using the while statement. The for statement has the
following syntax in WMLScript. The parts enclosed in brackets [] are
optional.
for
([expression1]; [expression2];
[expression3]) { WMLScript statement(s) }
expression1
is the initialization expression. It is executed before any WMLScript
statements in the for loop are executed. expression1 is
executed once only in the lifetime of the for statement. Very
often programmers initialize the loop counter here.
expression2
is the conditional expression that determines whether the for
loop should continue or stop. It is evaluated at the beginning of
each iteration. If it is true, the loop continues. If it is false or
invalid, the loop stops. If you omit expression2, the for
loop will continue forever unless the WMLScript interpreter
encounters a break statement,
which will be covered in a moment.
expression3
is executed after each iteration. Very often programmers increment
the loop counter here.
If
there is only one statement inside the curly brackets, the curly
brackets can be omitted.
The
following WMLScript example shows how to use the for statement
to execute a block of code 10 times:
var
result = 0; for (var counter=0; counter<10;
counter++) { result += 2; }
The
for loop in the above WMLScript example runs like this:
The
counter variable is declared and is initialized to 0.
The
WMLScript interpreter checks whether the condition "counter<10"
is true. As counter contains the value 0 now, the condition
evaluates to true.
The
statement "result += 2;" is executed.
The
WMLScript interpreter executes "counter++".
The
WMLScript interpreter checks whether the condition "counter<10"
is true. Now counter contains the value 1, so the condition
"counter<10" is true.
The
statement "result += 2;" is executed again.
...
If
you continue tracing the program, you will find that the for
loop stops after repeating 10 times. When the for
loop quits, the statement "result += 2;" has been
executed 10 times totally and so the result variable contains
the value 20.
Note
that the lifetime of the counter variable is till the end of
the function, although it is declared inside the parentheses of the
for statement. This behavior is different from some other
languages like Java. Feel free to go back to the earlier section
"Scope and Lifetime of WMLScript
Variables" if you forget what we have talked about.
Feedback Form (ExpandCollapse)
|
|