
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Loop Terminology
|
167
var words = ["Toronto", "is", "not", "the", "capital", "of", "Canada"];
var sentence;
var i = 0;
while (i < words.length) {
sentence += words[i]; // Add the current word to the sentence
// If it's not the last word...
if (i < words.length - 1) {
sentence += " "; // ...tack on a space
} else {
sentence += "."; // ...otherwise, end with a period
}
i++;
}
trace(sentence); // Displays: "Toronto is not the capital of Canada."
Nearly all loops involve some kind of counter (sometimes called an iterator or index
variable). Counters let us cycle sequentially through data. This technique is particu-
larly convenient when we determine the counter’s maximum limit using the
length
property of the array or string we want to manipulate, as we did in the preceding
example.
It’s also possible to create a loop whose end point doesn’t depend on a counter. As
long as the test expression of the loop eventually becomes
false, the loop will end.
Here, for example, we examine the document level stack of the Flash Player to deter-
mine the first vacant level:
var i = 0;
while (typeof eval("_level" + i) = = "movieclip") {
i++;
}
trace("The first vacant level is " + i);
// Now load a movie into the vacant level, knowing it's free
loadMovieNum("myMovie.swf", i);
For more information on document levels, ...