Show Navigation || Hide Navigation
Following on from our conditionals chapter which is all about decision making we turn to loops which is about repetition in your code. You may want your application to repeatedly loop a certain part of the code. ActionScript 3 uses loop structures to achieve this.
for Loop
The first loop we'll go over is the for loop. The for loop executes an finite number of times.
Example;
{
trace("five times");
}
The code above will trace "five times" in the output window 5 times. We start with the for keword declaring that it's a for loop. Inside the parentheses you'll notice some new characters such as (i++) This essentially means "add one each time". So our variable "i" has a value of 0, we then use basic math. The next line of code means;
"if i is less than five add one each time which will execute the trace statement".
while Loop
An alternative to the for lop is the while loop. Unlike the for loop which executes an finite number of times the while loop executes as long as the condition remains true.
Example;
var i:Number = 0;
while (i < siteName.length)
{
trace("site number" + i + "is" + siteName[i]);
i++;
}
In the code above their is an array on the first line which we haven't yet discussed in the AS3 Guide but will do in the next chapter. So for now see it as a variable with more than one piece of information. Inside the parentheses we have our conditions which state;
"while i is less than siteName.length execute the code".
In our trace statement it might look difficult to understand but really it isn't. In the green quotes we have "site number" and "is" these don't change but their position is key, after "site number" we add in the i value, then after "is" we add in our arrays with [i] allowing us to index through the array.
Test the movie and check the output window to get a better idea of what I am trying to explain.
This post is tagged AS3 Guide, loops, variables, while loop
Share This Post
Jobs


























One Comment
Doesn't it make more sense to write:
for (var i:int = 0; i < 5; i++)
{
trace("five times");
}
Incoming Links
Leave a Reply