Tutorial details: Using nested loops to sort through data
Difficulty Level: Intermediate
Requirements: Flash 5 and up
Assumed Knowledge: Basic for-loops and functions
File(s) to Download: nestedloops.zip
Online Example: None
The Power of Nested Loops
Nested loops are surprisingly powerful. They make for a great way of sorting through lots of data, by breaking it down in to smaller and smaller chunks.
Their power comes from the order in which they execute. We'll look at this shortly but now we're going to look at two ways of writing nested loops.
One way of writing nested loops is to 'bury' one loop inside another like this:
for (i=0; i<2; i++){
trace("outerloop");
for(j=0; j<2; j++){
trace("innerloop");
}
}
The other, my personal preference for reasons of clarity, is to put each loop inside a function and call the second loop from inside the first loop - like so:
myLoop1();
function myLoop1(){
for(i=0; i<2; i++){
trace("loop1 - outer loop");
myLoop2();
}
}
function myLoop2(){
for(j=0; j<2; j++){
trace("loop2 - inner loop");
}
}
You can copy and paste either bit of code in to the first frame of a new fla and test the movie (control -> test movie) to see the output. Let's do that with the second bit of code now and have a look at what those traces sent to the output window:
loop1 - outer loop
loop2 - inner loop
loop2 - inner loop
loop1 - outer loop
loop2 - inner loop
loop2 - inner loop
Notice the order in which the loops execute because it may not be as you expected.
They execute in the order 1,2,2,1,2,2 and not 1,2,1,2.
|