Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Syntax and Language Fundamentals > About statements > Repeating actions using loops > About creating and ending loops | |||
The following example shows a simple array of month names. A for loop iterates from 0 to the number of items in the array and displays each item in the Output panel.
var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var i:Number;
for (i = 0; i < monthArr.length; i++) {
trace(monthArr[i]);
}
When you work with arrays, whether they're simple or complex, you need to be aware of a condition called an infinite loop. An infinite loop, as its name suggests, is a loop with no end condition. This causes real problems--crashing your Flash application, causing your Flash document to stop responding in a web browser, or causing very inconsistent behavior of your Flash document. The following code is an example of an infinite loop:
// BAD CODE- creates an infinite loop
// USE AT OWN RISK!
var i:Number;
for (i = 0; i < 10; i--) {
trace(i);
}
The value of i is initialized to 0 and the end condition is met when i is greater than or equal to 10 and after each iteration the value of i is decremented. You can probably see the obvious error immediately: if the value of i decreases after each loop iteration, the end condition is never met. The results vary on each computer you run it on, and the speed at which the code fails depends on the speed of the CPU and other factors. For example, the loop executes about 142,620 times before displaying an error message on a given computer.
The following error message is displayed in a dialog box:
A script in this movie is causing Flash Player to run slowly. If it continues to run, your computer may become unresponsive. Do you want to abort the script?
When you work with loops (and especially while and do..while loops), always make sure that the loop can exit properly and does not end up in an infinite loop.
For more information on controlling loops, see Using a switch statement.
|
|
|
|