Microsoft® JScript Controlling Program Flow |
| Tutorial |
|
Fairly often, you need to have a script do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action.Microsoft JScript provides control structures for a range of possibilities. The simplest among these structures are the conditional statements.
JScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, some JScript code you've written is executed. (In the if...else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if...else statements are much more common.There are several kinds of conditions that you can test. The results of all conditional tests in JScript are Boolean, so the result of any test is a value of either true or false. You can freely test Boolean, numeric, and string values. See Operators for a complete list.
The following examples demonstrate syntaxes you can use with if and if...else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true, the statement or block of statements after the if is executed.
// The smash() function is defined elsewhere in the code. if (newShip) smash(champagneBottle,bow); // Boolean test of whether newShip is true. if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles") { // Both conditions must be true. theResponse = ("Is it a Crenshaw melon? <br> "); } var theReaction = ""; if ((lbsWeight ≶ 15) || (lbsWeight > 45)) { // Either condition may be true. theReaction = ("Oh, what a cute kitty! <br>"); } else theReaction = ("That's one huge cat you've got there! <br>"); var mo = theMonth.substring(0,3); if (mo == "Jan") { // String equality test. // January code here. } // ...And so on, through "Dec". /* A sphereVolume() function and a fight() function are defined elsewhere in the script, and the radius variable is declared and given a value. */ if (sphereVolume(radius) != 5440) { // The function must be executed for the test to be performed. fight(); }
JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon.
var hours = ""; // Code specifying that hours contains either the contents of // theHour, or theHour - 12. hours += (theHour >= 12) ? " PM" : " AM";
If several conditions are to be tested, testing continues only until passage or failure is clearly determined. That is, if three conditions must all be met and the second test fails, the third condition is not tested. Similarly, if only one of several conditions need be met, testing stops as soon as any one condition passes the test. If you have several conditions to be tested together and you know that one is more likely to pass or fail (depending on whether the tests are connected with OR or AND) than any of the others, you can speed execution of your script by putting that condition first in the conditional statement. This is particularly effective if the conditions to be tested involve execution of function calls or other code.
There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping. It is typically controlled by a conditional test of some variable, the value of which is changed each time the loop is executed. Microsoft JScript supports three loop constructs -- for loops, for...in loops, and while loops.
The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just before each time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After the loop is executed, the counter variable is updated before the next iteration begins.If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop results. You should be careful when you design loops.
/* The update expression ("icount++" in the following examples) is executed at the end of the loop, after the block of statements that forms the body of the loop is executed, and before the condition is tested. */ var howFar = 11; // Sets a limit of 11 on the loop. var sum = new Array(howFar); // Creates an array called sum with 11 members, 0 through 10. var theSum = 0; sum[0] = 0; for(var icount = 1; icount < howFar; icount++) { // Counts from 1 through 10 in this case. theSum += icount; sum[icount] = theSum; } var newSum = 0; for(var icount = 1; icount > howFar; icount++) { // This isn't executed at all. newSum += icount; } var sum = 0; for(var icount = 1; icount > 0; icount++) { // This is an infinite loop. sum += icount; }For historical reasons, the name of the counter variable in a loop usually begins with "i", "j", "k", "l", "m", or "n". Sometimes programmers use just the one letter. Though somewhat dated, this practice has the advantage of making it easy to recognize loop counter variables.
JScript provides a special kind of loop for stepping through all the properties of an object. The loop counter in a for...in loop steps through all indexes in the array. It is a string, not a number.
for (j in tagliatelleVerde) // tagliatelleVerde is an object with several properties { // Various JScript code statements. }
The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop.
var theMoments = ""; var theCount = 42; // Initialize the counter variable. while (theCount >= 1) { if (theCount > 1) { theMoments = "Only " + theCount + " moments left!"; } else { theMoments = "Only one moment left!"; } theCount--; // Update the counter variable. } theMoments = "BLASTOFF!";NOTE: Because while loops do not have explicit built-in counter variables, they are even more vulnerable to infinite looping than the other types. Moreover, partly because it is not necessarily easy to discover where or when the loop condition is updated, it is only too easy to write a while loop in which the condition, in fact, never does get updated. You should be extremely careful when you design while loops.
Microsoft JScript provides a special way to stop the execution of a loop. The break statement can be used to stop execution if some (presumably special) condition is met. The continue statement jumps immediately to the next iteration, skipping the rest of the code block but updating the counter variable as usual if the loop is a for or for...in loop. Please see the JScript Language Reference for more detail on these statements.NOTE: It is easy to create an infinite while loop with a continue statement. You should be extremely cautious when using these two together!
var theComment = ""; var theRemainder = 0; var theEscape = 3; var checkMe = 27; for (kcount = 1; kcount <= 10; kcount++) { theRemainder = checkMe % kcount; if (theRemainder == theEscape) { break; // Exits from the loop at the first encounter with a remainder that equals the escape. } theComment = checkMe + " divided by " + kcount + " leaves a remainder of " + theRemainder; } for (kcount = 1; kcount <= 10; kcount++) { theRemainder = checkMe % kcount; if (theRemainder != theEscape) { continue; // Selects only those remainders that equal the escape, ignoring all others. } // JScript code that uses the selected remainders } var theMoments = ""; var theCount = 42; // The counter is initialized here. while (theCount >= 1) { // if (theCount < 10) { // Warning! This use of continue would create an infinite loop! // continue; // } if (theCount > 1) { theMoments = "Only " + theCount + " moments left!"; } else { theMoments = "Only one moment left!"; } theCount--; // The counter is updated here. } theCount = "BLASTOFF!";
© 1996 by Microsoft Corporation.
file: /Techref/language/asp/js/303.htm, 10KB, , updated: 1996/11/22 10:12, local time: 2024/11/30 16:02,
18.227.49.73:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://sxlist.com/TECHREF/language/asp/js/303.htm"> Microsoft® JScript Language Tutorial </A> |
Did you find what you needed? |
Welcome to sxlist.com!sales, advertizing, & kind contributors just like you! Please don't rip/copy (here's why Copies of the site on CD are available at minimal cost. |
Welcome to sxlist.com! |
.