Working with For Statements


Advanced

For statements are an exciting kind of looping statement that many people find it easy to wrap their brains around when they’re first learning to program.

For statements are particularly easy to write in conjunction with arrays, as I show you in Chapter 6, “ Programming with Arrays.”

A while statement can be written that does exactly what a for statement does. But for statements are easy to understand because the “business end” of the statement—the initial value of the counter, the terminating condition, and the increment—are all in one place.

So that you can see exactly how for statements work, in a moment we’re going to reverse an input string. Later in this chapter, I show you how to do the same things using a do / while statement rather than a for statement. This will show you how the two compare.

The generalized form of the JavaScript for statement is as follows:

 for ( initial counter value ; condition ; increment)     statement 

This statement is itself usually a statement block of multiple statements enclosed in curly braces as I explained in Chapter 2, “ Understanding Types, Variables, and Statements” (see the “ Understanding Blocks ” section):

 for ( initial counter value ; condition ; increment)     {         statement1;         statement2;         ...         statementn;  } 

Do It Right!

As with any looping statement, it’s a good idea to create the statement framework before filling it in with other program statements. You’re less likely to make errors that way!

Reversing the String

It’s time to move along and write a program using a for loop that reverses the text string input by the user.

To Create a For Statement That Reverses a String:

Do It Right!
  1. Create the framework for a script within the body of an HTML document:

     <HTML> <BODY> <H1> <SCRIPT> </SCRIPT> </H1> </BODY> </HTML> 

  2. Create the scaffolding, or structure, for the for statement:

     for (   ;   ;  )   {   } 

  3. Initialize a variable before the for statement to hold the value of the reversed text string:

     var newString = ""; 

  4. Use the prompt function to obtain a string from the user:

     var newString = "";  var theString = prompt("Enter a string for reversal",""); 

    When the prompt function runs, the user will be prompted for input as shown in Figure 4-2. The value entered by the user will be assigned to the variable theString. (Because the default value is the empty string (""), if the user doesn’t enter text, that will be the value assigned.)

    click to expand
    Figure 4-2: The string that will be reversed is entered in a prompt box.

  5. In JavaScript, each string variable has an associated attribute, known as a property, called its length. As you might expect, a string’s length property contains the number of characters, including spaces, in a text string. (If the same letter occurs twice, it’s counted twice so that the value of the length property of the string "iiiuuu" is 6.) Use the length property to store the length of the string in a counter variable:

     var theString = prompt("Enter a string for reversal","");  var counter = theString.length; 

    (For more information on working with properties, see Chapter 7, “ Working with Objects.”)

  6. Create the iteration expressions for the for statement:

     var newString = "";  var theString = prompt("Enter a string for reversal","");  var counter = theString.length;  for (counter  ;counter > 0 ;counter -- )  {  } 

    This for condition means that the loop uses the variable counter to track iterations; it continues while counter > 0; and decrements the counter each time the loop is passed through.

    Note

    As a reminder, the decrement operator (--) subtracts one from its operand. So writing counter -- is equivalent to the statement counter = counter -1.

  7. Enter the statement (or statements) to be executed within the for loop:

     for (counter  ;counter > 0 ;counter -- )  {     newString += theString.substring(counter-1, counter);  } 

    This statement uses the substring method of the string object (this is all explained further in Chapter 7, “ Working with Objects ”) to extract a letter from the old string and add it to the new string. The extracted letter is assigned using concatenation to the right of the existing contents of the new string.

    In other words, the statement could be rewritten in a longer way as follows:

     newString = newString + theString.substring(counter-1, counter); 

    The first time the statement is executed, the new string is empty and the last letter of the old string is assigned to its leftmost place. The next time the statement is executed, the counter has already been decremented, meaning that the second-to-last letter of the old string is concatenated with the new string.

  8. Add a statement after the for loop to print the results:

     document.write(theString + " reversed is " + newString + "!"); 

  9. Run the program to verify that it works. As before, after the user enters a text string as shown in Figure 4-2 and clicks OK, the reversed string is displayed (see Figure 4-3). Listing 4-1 shows the complete code used.

    Listing 4.1: Using a for Loop to Reverse a String

    start example
     <HTML> <BODY> <H1> <SCRIPT>        var newString = "";        var theString = prompt("Enter a string for reversal","");        var counter = theString.length;        for (counter  ;counter > 0 ;counter -- )        {           newString += theString.substring(counter-1, counter);        }        document.write(theString + " reversed is " + newString + "!");     </SCRIPT> </H1> </BODY> </HTML> 
    end example

    click to expand
    Figure 4-3: The reverse text is displayed in the browser.

If the code in this example seems difficult to you, don’t worry about it too much! It has introduced a number of new concepts in addition to the for loop, including the prompt function, the length property of a text string, and the substring method of a string.

Advanced

These aren’t easy things to wrap one’s brain around. The best thing you can do is play with the code in the example. What happens if you change things around a little?

Tip

A variation of the for statement, the for/in statement, is used with JavaScript objects. For more information about for/in, see Chapter 7, “ Working with Objects.”




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

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