Creating JavaScript for Loop Statements

Creating JavaScript for Loop Statements

Using loops , you can execute code as many times as you wantwhich is one of the things computers excel at. The most basic loop is the for loop statement, and here's what this statement looks like in general:

 for (  initialization;   test;   increment  ) {  code  } 

Here's what's happening: You place an expression in the initialization part of the for loop (which often initializes a variable, called a loop index, to 0), Then you insert a test condition in the test part of the loop to be tested each time the code in the loop has been executed. If the test is false, the loop ends (often the test condition checks whether the value in the loop index exceeds a specified maximum value). On the other hand, if the test condition is true, the body of the loop is executed and the code in the increment part of the loop is executed to get the loop ready for the next iteration (often by incrementing the loop index).

Here's an example to make this clear. In this case, I'll set up a loop to execute 10 times; each time, it will print out the value in a loop index. This example works by setting a loop index variable named loopIndex to to start; then it increments it each time when the loop code has executed (using the increment operator, ++ ) and checks to make sure the loop index does not exceed 10 . When the loop index does exceed 10 , the loop terminates. Here's the code (the HTML <BR> element makes the Web browser skip to the next line):

Listing ch06_08.html
 <HTML>      <HEAD>         <TITLE>             Using the for Statement         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Using the for Statement             </H1>         </CENTER>         <SCRIPT LANGUAGE = "JavaScript">  for(var loopIndex = 1; loopIndex <= 10; loopIndex++){   document.writeln("The loop index value is " +   loopIndex + "<BR>")   }  </SCRIPT>     </BODY> </HTML> 

Here's another thing to note in this example: Because loopIndex is a variable that we're using in our code, we must declare it. JavaScript allows you the shortcut of declaring a variable like this right in the for loop itself, and you can see the var statement inside the initialization part of the for loop. This is a common practice, and I'm including it here because you'll see it often.

When you open this page in a browser, you'll see a message displaying the value of the loop index from 1 to 10 , as you see in Figure 6-8.

Figure 6-8. Using a JavaScript for loop in Internet Explorer.

graphics/06fig08.gif



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

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