Previous Example-|-Next Example-|-Return to Chapter Listing

Example 6.14:
Mimicking a 'for' Loop with Nested if Statements


The button calls function1(), which executes the code which is equivalent to the 'for' loop in Example 6.13. Compare the scripts, and you'll see the 'for' loop is far simpler:


This is the script we used: <SCRIPT LANGUAGE="JavaScript"> <!-- function function1() { var i = 1; if (i < 4) { alert("The value in i is " + i ) i++ // i now equals 2 if (i < 4) { alert("The value in i is " + i ) i++ //i now equals 3 if (i < 4) { alert("The value in i is " + i ) i++ //i now equals 4 if (i < 4) { //i is not less than 4 so this is false alert("The value in i is " + i ) i++ } } } } } //--> </SCRIPT> </HEAD> <BODY> <BR> <form> <input type="button" value=" Button A " onClick="function1()"> </form>
Previous Example-|-Next Example-|-Return to Chapter Listing