Loops

By using loops, you can cause actions to be repeated. Loops can be useful in reducing the amount of code you need to write. In the next sections, we'll take a quick look at four kinds of loops before demonstrating them in Code Listing 9-5.

for Loops

One of the most common types of loop is the for loop, typically used to perform actions a set number of times. The following line of code demonstrates a basic for loop that displays 10 successive Alert dialog boxes:

 for (var i=1;i<=10;i++){alert("This is alert number "+i)} 

A for loop begins with the word for. The code that follows, in parentheses, includes the initialization, which specifies a counting variable and gives it an initial value. The initialization is followed by a semicolon and a test, which is a Boolean expression. If the test evaluates to true, the actions specified by the code in the curly braces will be executed; if the test evaluates to false, the code will not run. Thus, in the example shown here, the loop will be run as long as i is less than or equal to 10. The next part of the code includes a semicolon and an increment, which specifies how the counting value should change. We used i++, which adds 1 to i. Finally the code specifies the actions to be taken, enclosed in braces.

for...in Loops

You can use a for...in loop to step through all of an object's properties or all of the indexes in an array. For example, the following line of code will print each index of an array named myArray on a new line:

 for (i in myArray){document.write(myArray[i]+"<BR>")} 

On the CD, you will find a useful Web page called ObjInfo.htm in the Tools folder. This page takes an object specified by the user and uses a for...in loop to step through and display all of its properties. Figure 9-5 shows the information ObjInfo.htm displays about the document object.

click to view at full size.

Figure 9-5. Information about the document object.

while Loops

A basic while loop specifies an action to be taken as long as a Boolean test returns true. Like a for loop, a while loop can be used to count, and you can also use it to test the values of data. This type of loop consists of the word while followed first by a Boolean test and then by the code specifying the actions that should occur. The following line of code demonstrates a basic while loop that displays 10 successive Alert dialog boxes (assuming that the variable i starts out with a value of 1):

 while(i<=10){alert("This is alert number "+i);i++} 

do...while Loops

A variation of the while loop, called a do...while loop, performs a set of actions once and then repeats them as long as a condition is met. Its primary difference from the other loops is that the action is always performed at least once, because the test occurs at the end of the loop. The following code snippet will cause one alert to be displayed, even though 5 is not less than or equal to 3.

 i=5; do{alert("This is alert number "+i);i++}while(i<=3) 

If i had been set equal to 1, three alert boxes would have resulted.

Code Listing 9-5 shows the different loops in use. In this sample, the user is asked to enter five numbers, which are then displayed on screen. Let's examine each part of this sample. First we declared a new array and filled it with three items of data by using a for loop. (Because arrays are zero-ordered, we started at 0 and counted to 2 rather than starting at 1 and counting to 3.) Next we used a for...in loop to allow the user to guess each number in the array.

A while loop determines whether the user's guess is correct; if it is not, the program asks the user to try again. This continues until the user guesses correctly or clicks cancel. Next we used an if... statement to test whether the user clicked cancel to quit. If the user clicks cancel, an if...else statement is used to present a dialog box that asks the user whether he or she wants to quit entirely or go on to the next number. If the user chooses to quit, the break expression is used. The break expression can be used to exit all types of loops. If the user chooses to move on to the next number, the specified action is continue, which goes on to the next iteration of our for...in loop and thus continues to the next number. Finally, after the program is finished, the user sees a goodbye message in the browser window.

Code Listing 9-5.

 <HTML> <HEAD> <TITLE>Listing 9-5</TITLE> <SCRIPT LANGUAGE="JavaScript"> var numArray=new Array for (var i=0;i<=2;i++){   numArray[i]=Math.ceil(Math.random()*4) } alert("You will be asked to guess three numbers I have picked.") for (j in numArray){   guess=prompt("Guess between 1 and 4. Cancel will exit.","")   while((guess!=numArray[j])&&(guess!=null)){     guess=prompt("Nope! Try again or type 0 to quit.","")   }   if (guess==null){     if(confirm("OK to quit, Cancel to guess the next number.")){       break     }     else{continue}   }   alert("That's right!") } alert("Goodbye!") </SCRIPT> </HEAD> </HTML> 

When using any type of loop, you should be careful to ensure that you do not end up in an infinite loop. An infinite loop is one that is never exited. This can occur in many different ways and is more common with while loops than for loops. For example, the following snippet of code will result in an infinite loop.

 i=0 while(i<=10){alert("This is alert number "+i);a++} 

The counter variable i is never incremented; the variable a is incremented instead. Thus, i is always less than 10, and the loop is never exited.

NOTE
Caution: Do not execute this line of code in a browser. If you do, your browser is likely to hang. If this does occur (and you are running Microsoft Windows 95, Windows 98, or Microsoft Windows NT), press the Ctrl, Alt, and Del keys simultaneously. This should bring up a window that will allow you to select the browser that is not responding and choose End Task, which will stop the program.

Internet Explorer 5 also supports new features called Conditional Compilation Conditional Comments. Because they can be helpful for writing cross browser code, they are covered in Chapter 23.

The past several chapters have focused on the basics of scripting. The next chapter will take a look at ways to trap errors and debug your code.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

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