Working with Loops


Loops let you execute the same code over and over; although the code is the same each time through, the data you work on changes. That’s particularly important for computers, which are great at handling large sets of data to work on. The first loop you’re going to see in this chapter is the most popular one: the for loop.

Looping with the for loop

You might be in charge of inventory for a huge company, and be charged with determining the average price of all items in stock. You could do that handily with a for loop, which lets you loop over a number of items. The for loop is the most commonly used loop in JavaScript, and here’s how it works:

 for ([initial-expression]; [condition]; [increment-expression]) {     statements }

You usually use a for loop with a loop index, also named a loop counter. A loop index is a variable that keeps track of the number of times the loop has been executed. In the initial-expression part, you usually set the loop index to a starting value; in the condition part, you test that value to see whether you still want to keep on looping; and the increment-expression lets you increment the loop counter.

It’s time for an example. Say, for example, that you wanted to add the numbers from 1 to 1,000 and display the result. Here’s what that would look like in an example using the for loop, for.html:

 <html>   <head>     <title>Using a for loop</title>     <script language="javascript">        function showMessage()       {         var loopIndex;         var total = 0;         for(loopIndex = 1; loopIndex <= 1000; loopIndex++) {           total += loopIndex;         }         document.getElementById('targetDiv').innerHTML =           "The total of 1 to 1000 is " + total;       }     </script>   </head>   <body onload="showMessage()">     <h1>Using a for loop</h1>     <div >     </div>     </body> </html>

Here’s the for loop in this example:

 for(loopIndex = 1; loopIndex <= 1000; loopIndex++) {   total += loopIndex; }

Note how this works: the loop index is initialized to 1, and the body of the loop is executed with that value in loopIndex. After the loop is executed, the expression loopIndex++ is executed; the ++ operator (see Table 2.1) increments its value by 1, so loopIndex ends up holding 2. Then JavaScript tests whether the condition is still true. Because that condition is loopIndex<=1000-that is, loopIndex is less than or equal to 1000-the condition is true, and the body of the loop is executed again. And so the loop keeps going until all the numbers from 1 to 1000 have been added together.

What’s the result? You can see the answer in Figure 2.20; adding all the numbers from 1 to 1,000 gives you 500,500.

Imagine doing this calculation by hand. Adding 1 to 1,000 would take a long time, and it’s a calculation that’s prone to error. But using JavaScript, it’s no problem.

Besides the for loop, there’s another loop you should know about-the while loop. The while loop lets you keep executing the body of the loop while a test condition is true, and it’s coming up next.

image from book
Figure 2.20: Adding 1 to 1000 with the for loop

Looping with the while loop

Besides the for loop, you can also use the while loop to loop over code. In fact, the while loop is simpler than the for loop-it just keeps looping while a test condition is true:

 while (condition) {     statements }

It’s time for an example. This example is going to loop over a number of customers, from Anne to Zack, searching for a particular customer. How can you keep track of your customers? You can use an array, another part of JavaScript. Unlike simple variables, arrays can hold multiple data items, and they’re indexed with a numeric index. For example, say you wanted to create an array named customers to keep track of your customers; you could do that like this:

 var customers = new Array(8);

This creates an array of eight customers. Now you can address each of the eight as you would a simple variable, using an array index, which is placed inside square braces like this:

 customers[0] = "Anne"; customers[1] = "Tom"; customers[2] = "Frank"; customers[3] = "Sam"; customers[4] = "Elizabeth"; customers[5] = "Nancy"; customers[6] = "Ralph"; customers[7] = "Zack";

Notice that the first customer has array index 0. That’s because JavaScript arrays always start with array index 0. Now you can refer to each element in the array by number. For example, cus tomers[1] holds Tom, customers[3] holds Sam, and so on. In this way, an array functions as a collection of simple variables, indexed by number.

Because arrays are indexed with numbers, they’re perfect to use with loops because they act as a set of variables you can access by number, and you can increment that number in a loop (for example, that number can be a loop index in a for loop).

In this example, you want to search your customers for a particular customer, say Nancy. That is, you want to keep looping until you find Nancy. To check for equality, you can use the JavaScript == operator like this:

 customers[loopIndex] == "Nancy"

This expression will be true when customers[loopIndex] holds the word “Nancy.”

However, that’s not exactly what you want in this case. You want to keep looping with the while loop while the current customer is not Nancy (the idea is to find Nancy). So you’d want to use the not equals, !=, operator like this as the test condition of the while loop:

 customers[loopIndex] != "Nancy"

Here’s what the while loop is going to look like:

 var loopIndex = 0; while(customers[loopIndex] != "Nancy"){   loopIndex++; }

When this loop ends, the loopIndex variable should hold the index of the array element that holds Nancy. But there’s a problem here: what if there’s no Nancy in the customers list? You can put a cap on the value that loopIndex can take so that you don’t try searching past the end of the array. You do that by determining the number of elements in the array using the array’s length property; this property returns 8 for the customers array because it has eight elements. However, because this example uses the array index, which goes from 0 to 7, you have to compare that loop index to customers.length - 1, not just to customers.length.

So how do you add the condition loopIndex < customers.length - 1 to the while loop’s current condition, customers[loopIndex] != "Nancy"? You can use the && “and” operator (see Table 2.1), which insists that two conditions be true before the overall condition is true; here’s what it looks like in the while loop:

 while(customers[loopIndex] != "Nancy" && loopIndex <   customers.length - 1){   loopIndex++; }

There’s also an “or” operator, ||, that makes a condition true if one or the other of two conditions are true-a||b is true if either a or b is true, or both a and b; otherwise, it’s false.

Okay, this while loop is ready to go. Here’s what the Web page that searches for Nancy, while.html, looks like:

 <html>   <head>     <title>Using the while loop</title>     <script language="javascript">       function showMessage()       {         var loopIndex = 0, customers = new Array(6);         customers[0] = "Anne";         customers[1] = "Tom";         customers[2] = "Frank";         customers[3] = "Sam";         customers[4] = "Elizabeth";         customers[5] = "Nancy";         customers[6] = "Ralph";         customers[7] = "Zack";         while(customers[loopIndex] != "Nancy" && loopIndex <           customers.length - 1){           loopIndex++;         }         if(loopIndex < customers.length - 1){           document.getElementById('targetDiv').innerHTML =           "I found Nancy at customer index " + loopIndex;         }         else {           document.getElementById('targetDiv').innerHTML =           "I did not find Nancy.";         }       }     </script>   </head>   <body onload="showMessage()">     <h1>Using the while loop</h1>     <div >     </div>   </body> </html>

So will this Web page be able to find Nancy? Take a look at Figure 2.21. Yes, it did indeed find Nancy.

image from book
Figure 2.21: Finding Nancy with the while loop

At this point, you’ve got all the JavaScript you’re going to need in this book under your belt. You’ve seen basic JavaScript, working with variables, operators, the if statement, and the loops. There’s just one more skill you’re going to need: working with HTML controls such as buttons in Web pages.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

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