Loop Exceptions


In general, a loop continues to perform iterations until its condition is no longer true. However, you can use two actions to change this behavior: continue and break.

With the continue action, you can stop the current iteration (that is, no further actions in that iteration will be executed) and jump straight to the next iteration in a loop. For example:

    var total:Number = 0;     var i:Number = 0;     while(++i <= 20) {       if(i == 10) {         continue;       }       total += i;     }


The while statement in this script loops from 1 to 20, with each iteration adding the current value of i to a variable named total until i equals 10. At that point, the continue action is invoked, which means that no more actions are executed on that iteration, and the loop skips to the eleventh iteration. This would create the following set of numbers:

    1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20


Notice that there is no number 10, indicating that no action occurred on the tenth loop.

The break action is used to exit a loop, even if the condition that keeps the loop working remains true. For example:

    var total:Number = 0;     var i:Number = 0;     while(++i <= 20) {       total += i;       if(total >= 10) {         break;       }     }


This script increases the value of a variable named total by 1 with each iteration. When the value of total is 10 or greateras checked by an if statementa break action occurs and the while statement halts, even though it's set to loop 20 times.

In practice, the break command is used more often than the continue command because programmers often use if statements rather than continue to bypass actions in a loop.




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net