1.5. Repeating an Operation Many Times
Problem
You want to perform a task multiple times within a single frame.
Solution
Use a loop to perform the same task multiple times within a single
frame. For example, you can use a for statement:
for (var i = 0; i < 10; i++) {
// Display the value of i.
trace(i);
}Discussion
When you want to execute the same action (or slight variations
thereof) multiple times within a single frame, use a looping
statement to make your code more succinct, easier to read, and easier
to update. You can use a while statement or a
for statement for this purpose, but generally a
for statement is the better choice. Both
statements achieve the same result, but the for
statement is more compact and more familiar to most programmers.
The syntax of a for statement
consists of five basic parts:
-
The
forkeyword Every
forstatement must begin with aforkeyword.- Initialization expression
The loop typically employs an
index variable(a.k.a. aloop counter) that is initialized when the statement is first encountered. The initialization is performed only once regardless of how many times the loop is repeated.- Test expression
A loop should include a test expression that returns
trueorfalse. The test expression is evaluated once each time through the loop. Generally, the test expression compares the index variable to another value, such as a maximum number of loop iterations. The overall expression must evaluate totruefor theforstatement’s body to execute (contrast this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access