The while LoopAnother powerful loop in JavaScript is the while loop. When you want a loop that uses a loop index, you naturally think of a for loop. However, you also might want a loop that doesn't use a loop index at allyou might want to loop only until a certain condition becomes false (such as when you haven't yet found the data item for which you're searching an array). That's where the while loop comes in. This loop evaluates an expression, and if it is true, executes a set of statementsno loop index needed. The loop keeps repeating as long as the specified condition is true. while ( condition ) { statements } The following parts comprise this loop:
Like the for and for in loops , the while loop has been around a long time, as you see in Table 3.3. Table 3.3. The while Loop
Here's an example. In this case, I'll search an array for a person named Claire using a while loop; when I find Claire, I'll end the loop. Here's what the code looks like: (Listing 03-04.html on the web site)<HTML> <HEAD> <TITLE> Using the while Loop </TITLE> </HEAD> <BODY> <H1>Using the while Loop</H1> <SCRIPT LANGUAGE="JavaScript"> <!-- var index = 0, data = new Array(5) data[0] = "Fank" data[1] = "Tom" data[2] = "Claire" data[3] = "Sara" data[4] = "Jane" while(data[index] != "Claire"){ index++ } alert("Found Claire at index " + index) // --> </SCRIPT> </BODY> </HTML> You can see the results in Figure 3.5, where we've found Claire.That's all it takes. Figure 3.5. Using a while loop.
Here's one thing to note about the while loop: The condition is tested before the loop's body is executed even once. That's a problem where the code in the loop's body must be evaluated before the condition can be checked (as, for example, when you must perform some complex calculation to determine whether a result is over the maximum possible value). In cases like these, you can use the new do while loop, which is just like a while loop, but where the loop's condition is checked at the end of each loop iteration, not before each iteration. |