Section 5.7. Control Statements


5.7. Control Statements


Stops execution of the current loop and returns control to the next script statement following the end of the current loop. Note that without a label parameter, the scope of the break statement is its own loop. To break out of a nested loop, assign labels to each nested layer, and use the desired label as a parameter with the break statement. See the label statement.


Syntax

 break [label] 


Example

See the label statement.


See try.


Stops execution of the current iteration through the loop and returns to the top of the loop for the next pass (executing the update expression if one is specified in a for loop). If you are using nested loop constructions, assign labels to each nested layer, and use the desired label as a parameter with the continue statement. See the label statement.


Syntax

 continue [label] 


Example

 outerLoop: for (var i = 0; i <= maxValue1; i++) {     for (var j = 0; j <= maxValue2; j++) {         if (j*i == magic2) {             continue outerLoop;         }     } } 


Executes statements in a loop while a condition is true. Because the condition is tested at the end of the loop, the statements inside it are always executed at least one time. It is imperative that the expression that makes up the condition have some aspect of its value potentially altered in the statements. Otherwise, an infinite loop occurs.


Syntax

 do {    statements } while (condition) 


Example

 var i = 1; do {     window.status = "Loop number " + i++; } while (i <= 10) window.status = ""; 


This is a construction that allows repeated execution of statements, usually for a controlled number of times.


Syntax

 for ([initExpression]; [condition]; [updateExpression]) {     statements } 


Example

 var userEntry = document.forms[0].entry.value; var oneChar; for (var i = 0; i < userEntry.length; i++) {     oneChar = userEntry.charAt(i);     if (oneChar < "0" || oneChar > "9") {         alert("The entry must be numerals only.");     } } 


This is a variation of the regular for loop that can extract the property names and values of an object. Only properties (and methods in Mozilla, Safari, and Opera) that are set to be enumerable by the browser internals appear in the output of this construction.

In the E4X context, the object reference is an instance of an XML object, and is automatically treated as an XMLList. As such, the variable acts like an index to the list during the iterations. For example, if myXml is an XMLList with a dozen records, each of which has an element named productID, you could iterate through all of those nested elements as follows:

 for (var i in myXml..productID) {     alert("Product docPubcolor">Syntax

 for ([var] varName in objectRef) {     statements } 


Example

 function showProps( ) {     objName = "image";     obj = document.images[0];     var msg = "";     for (var i in obj) {         msg += objName + "." + i + "=" + obj[i] + "\n";     }     alert(msg); } 


This is a variation of the for-in loop tailored for E4X implementations. Note that in the E4X context, the for-in construction assigns an index to the variable. In contrast, the for-each-in construction assigns an object reference to the variable, facilitating iteration through the objects within an XMLList.


Syntax

 for each ([var] varName in objectRef) {     statements } 


Example

 for (var i in myXml..productID) {     alert("Product docList"> 

This is a simple conditional statement that provides one alternate execution path.


Syntax

 if (condition) {     statement(s) if true } 


Example

 if (myDateObj.getMonth( ) == 1) {     calcMonthLength( ); } 


This is a conditional statement that provides two execution paths depending on the result of the condition. You can nest another if or if-else statement inside either path of the if-else statement.


Syntax

 if (condition) {     statement(s) if true } else {    statement(s) if false } 


Example

 var theMonth = myDateObj.getMonth( ); if (theMonth == 1) {     monLength = calcLeapMonthLength( ); } else {     monLength = calcMonthLength(theMonth); } 


You can assign a label identifier to any block of executing statements, including control structures. The purpose of the label is to allow break and continue statements within deeply nested control structures to exit to a nested level that may be at levels beyond the scope of the normal break and continue statements.


Syntax

 labelName: 


Example

 outerLoop: for (var i = 0; i <= maxValue1; i++) {     for (var j = 0; j <= maxValue2; j++) {         if (i == magic1 && j == magic2) {             break outerLoop;         }     } } 


Stops execution of the current function. A return statement can be located anywhere within the function, including inside control structures. You can optionally specify a value to be returned to the calling statement. This return value can be any JavaScript data type. If a return statement that returns a value is in a loop or other control structure, there must be a return statement for each branch of the execution tree, including a default return statement if execution should reach the main execution scope near or at the end of the function.


Syntax

 return [value] 


Example

 function validateNumber(form) {     var oneChar;     for (var i = 0; i < userEntry.length; i++) {         oneChar = form.entry.value.charAt(i);         if (oneChar < "0" || oneChar > "9") {             return false;         }     }     return true; } 


Provides a shortcut to execution paths for numerous conditions of an expression. The optional break statement at the end of each case block shortcuts execution of the switch statement, and also prevents the inadvertent execution of the default block, if present.


Syntax

 switch (expression) {     case label1:         statements         [break;]    case label2:         statements         [break;]     ...     [default:        statements] } 


Example

 var productList = document.forms[0].prodList; var chosenItem = productList.options[productList.selectedIndex].value; switch(chosenItem) {     case "Small Widget":         document.forms[0].price.value = "44.95";         break;     case "Medium Widget":         document.forms[0].price.value = "54.95";         break;     case "Large Widget":         document.forms[0].price.value = "64.95";         break;     default:         document.forms[0].price.value = "Nothing Selected"; } 


Triggers an exception condition, passing a value along with the exception. Although the value you pass can be a simple string, ideally you should pass an instance of the JavaScript Error object filled with sufficient information for a catch statement to act intelligently on the error. A throw statement must be enclosed in the try portion of a try-catch construction.


Syntax

 throw value; 


Example

 function processNumber(inputField) {     try {         var inpVal = parseInt(inputField.value, 10);         if (isNaN(inpVal)) {             var msg = "Please enter a number only.";             var err = new Error(msg);             if (!err.message) {                 err.message = msg;             }             throw err;         }         // process number     }     catch (e) {         alert(e.message);         inputField.focus( );         inputField.select( );     } } 


This construction provides a nondisruptive way to trap for errors (exceptions) and handle them gracefully. Both parts of this exception-handling construction are required. If an error occurs in the TRy portion, execution immediately branches to the catch portion, where your scripts can display alert dialogs, modify data, or any other task that keeps the JavaScript interpreter from triggering a disruptive error message. Exceptions that occur naturally (i.e., they are not thrown by a tHRow statement) pass an instance of the Error object as a parameter to the catch section. Statements inside the catch section can examine properties of the error object to determine how to handle exceptions that land there. Thus, one catch portion can handle errors of various types.

You can use TRy-catch constructions only in browsers that support them. To protect older browsers from seeing this construction, place all affected code inside a <script> tag that explicitly requires JavaScript 1.5 or later (with the language = "JavaScript1.5" or later attribute).


Syntax

 try {    statement(s) that could cause error } catch (errorInfo) {    process error(s) gracefully } 


Example

 function insertOneNode(baseNode, newNode, position) {     try {         baseNode.insertBefore(newNode, baseNode.childNodes[position]);     }     catch (e) {         // handle W3C DOM Exception types         switch (e.name) {             case "HIERARCHY_REQUEST_ERR" :                 // process bad tree hierarchy reference                 break;             case "NOT_FOUND_ERR" :                 // process bad refNode reference                 break;             default :                 // process all other exceptions         }     }     return true; } 


Executes statements in a loop as long as a condition is true. Because the condition is tested at the beginning of the loop, it is conceivable that under the right conditions, the statements inside the loop do not execute. It is imperative that the expression that makes up the condition have some aspect of its value potentially altered in the statements. Otherwise an infinite loop occurs.


Syntax

 while (condition) {     statements } 


Example

 var i = 0; while (!document.forms[0].radioGroup[i].checked) {     i++; } alert("You selected item number " + (i+1) + "."); 


The with statement adds an object to the scope of every statement nested within. This can shorten the code of some statement groups that rely on a particular object reference. Note that with constructions are generally very inefficient. You can achieve better performance by assigning the object reference to a local variable, and using that variable in your function.


Syntax

 with (objectRef) {     statements } 


Example

 with (document.forms[0]) {     name1 = firstName.value;     name2 = lastName.value;     mail = eMail.value; } 


You can turn a function into what is called a generator by inserting the yield keyword into a looping section of the function. Such functions need to be assigned to a variable or as a property value so that the reference can subsequently iterate through the looping section one loop at a time.

When the function is initially invoked, all statements up to the looping section execute as normal. But execution pauses temporarily just before the yield statement. The yield statement can return a value, just like a return statement, but the generator function remains alive, waiting for iterative stepping through the loop section.

To obtain the yielded value, invoke the next( ) method on the function (just like the next( ) method of an iterator object). If there are statements in the function following the yield statement, they execute at this time (perhaps acting on the values of local variables inside the function), but pause in the next time through the loop, just before the yield statement.


Syntax

 function myFunction( )    statements     while (true)        yield value;         statements     } } 


Example

 function getWords(txt) {     var words = txt.split(" ");     for (var i = 0; i < words.length; i++) {         yield words[i].length;     } } function getAverageWordLength(txt) {     var lengthCounter = getWords(txt);     var count = 0;     var total = 0;     try {         while (total += lengthCounter.next( )) {             count++;         }     }     catch(e) {}     alert("Average word length is: " + (total/count).toFixed(2) + " characters."); } 




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

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