1 / 65

Chapter 10 - JavaScript: Functions

Chapter 10 - JavaScript: Functions. Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3 Programmer-Defined Functions 10.4 Function Definitions 10.5 Random-Number Generation 10.6 Example: Game of Chance 10.7 Duration of Identifiers 10.8 Scope Rules

nydia
Download Presentation

Chapter 10 - JavaScript: Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3 Programmer-Defined Functions 10.4 Function Definitions 10.5 Random-Number Generation 10.6 Example: Game of Chance 10.7 Duration of Identifiers 10.8 Scope Rules 10.9 JavaScript Global Functions 10.10 Recursion 10.11 Example Using Recursion: Fibonacci Series 10.12 Recursion vs. Iteration 10.13 JavaScript Internet and World Wide Web Resources

  2. Prompt for the user to input three integers. Call function maximum and pass it the value of variables value1, value2 and value3. Variables x, y and z get the value of variables value1, value2 and value3, respectively. Method max returns the larger of the two integers passed to it. The return statement passes the maximum value back to the calling function. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.3: maximum.html --> 6 <!-- Maximum function --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Finding the Maximum of Three Values</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var input1 = 15 window.prompt( "Enter first number", "0" ); 16 var input2 = 17 window.prompt( "Enter second number", "0" ); 18 var input3 = 19 window.prompt( "Enter third number", "0" ); 20 21 var value1 = parseFloat( input1 ); 22 var value2 = parseFloat( input2 ); 23 var value3 = parseFloat( input3 ); 24 25 var maxValue = maximum( value1, value2, value3 ); 26 27 document.writeln( "First number: " + value1 + 28 "<br />Second number: " + value2 + 29 "<br />Third number: " + value3 + 30 "<br />Maximum is: " + maxValue ); 31 32 // maximum method definition (called from line 25) 33 function maximum( x, y, z ) 34 { 35 return Math.max( x, Math.max( y, z ) ); Maximum.html

  3. 36 } 37 // --> 38 </script> 39 40 </head> 41 <body> 42 <p>Click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html> Maximum.htmlProgram Output

  4. The for loop creates 4 rows with 5 cells of a table. Method floor rounds the number generated by method random down. Each cell is populated with a random number generated by method random. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.4: RandomInt.html --> 6 <!-- Demonstrating the Random method --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Shifted and Scaled Random Integers</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var value; 15 16 document.writeln( 17 "<table border = \"1\" width = \"50%\">" ); 18 document.writeln( 19 "<caption>Random Numbers</caption><tr>" ); 20 21 for ( var i = 1; i <= 20; i++ ) { 22 value = Math.floor( 1 + Math.random() * 6 ); 23 document.writeln( "<td>" + value + "</td>" ); 24 25 // write end and start <tr> tags when 26 // i is a multiple of 5 and not 20 27 if ( i % 5 == 0 && i != 20 ) 28 document.writeln( "</tr><tr>" ); 29 } 30 31 document.writeln( "</tr></table>" ); 32 // --> 33 </script> 34 35 </head> RandomInt.html

  5. 36 <body> 37 <p>Click Refresh (or Reload) to run the script again</p> 38 </body> 39 </html> RandomInt.htmlProgram Output

  6. If the value of firstRoll is true, then function rollDice is called. If function rollDice returns a value of 7 or 11, theplayer wins and the break statement causes program control proceeds to the first line after the switch structure. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.6: Craps.html --> 6 <!-- Craps Program --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Program that Simulates the Game of Craps</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 // variables used to test the state of the game 15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 16 17 // other variables used in program 18 var firstRoll = true, // true if first roll 19 sumOfDice = 0, // sum of the dice 20 myPoint = 0, // point if no win/loss on first roll 21 gameStatus = CONTINUE_ROLLING; // game not over yet 22 23 // process one roll of the dice 24 function play() 25 { 26 if ( firstRoll ) { // first roll of the dice 27 sumOfDice = rollDice(); 28 29 switch ( sumOfDice ) { 30 case7: case11: // win on first roll 31 gameStatus = WON; 32 // clear point field 33 document.craps.point.value = ""; 34 break; 35 case2: case3: case12: // lose on first roll Craps.html

  7. If function rollDice retursn a 2, 3 or 12, the player loses and the break statement causes control to proceed to first line after the switch structure. If the value of firstRoll is false, function rollDice is called to see if the point has been reached. If the value returned by function rollDice equals the value of variable myPoint, the player wins because the point has been reached. If the values returned by function rollDice equals 7, the player loses. window method status displays a message in the status bar of the browser. 36 gameStatus = LOST; 37 // clear point field 38 document.craps.point.value = ""; 39 break; 40 default: // remember point 41 gameStatus = CONTINUE_ROLLING; 42 myPoint = sumOfDice; 43 document.craps.point.value = myPoint; 44 firstRoll = false; 45 } 46 } 47 else { 48 sumOfDice = rollDice(); 49 50 if ( sumOfDice == myPoint ) // win by making point 51 gameStatus = WON; 52 else 53 if ( sumOfDice == 7 ) // lose by rolling 7 54 gameStatus = LOST; 55 } 56 57 if ( gameStatus == CONTINUE_ROLLING ) 58 window.status = "Roll again"; 59 else { 60 if ( gameStatus == WON ) 61 window.status = "Player wins. " + 62 "Click Roll Dice to play again."; 63 else 64 window.status = "Player loses. " + 65 "Click Roll Dice to play again."; 66 67 firstRoll = true; 68 } 69 } 70 Craps.html

  8. Function rollDice is called to simulate the rolling of two dice on the craps table. Methods random and floor are used to generate the values for the two dice. Referencing the names of form elements in the XHTML document, the vlaues of the dice are placed in their respective form fields. 71 // roll the dice 72 function rollDice() 73 { 74 var die1, die2, workSum; 75 76 die1 = Math.floor( 1 + Math.random() * 6 ); 77 die2 = Math.floor( 1 + Math.random() * 6 ); 78 workSum = die1 + die2; 79 80 document.craps.firstDie.value = die1; 81 document.craps.secondDie.value = die2; 82 document.craps.sum.value = workSum; 83 84 return workSum; 85 } 86 // --> 87 </script> 88 89 </head> 90 <body> 91 <form id ="craps" action = ""> 92 <table border ="1"> 93 <caption>Craps</caption> 94 <tr><td>Die 1</td> 95 <td><input name ="firstDie"type ="text" /> 96 </td></tr> 97 <tr><td>Die 2</td> 98 <td><input name ="secondDie"type ="text" /> 99 </td></tr> 100 <tr><td>Sum</td> 101 <td><input name ="sum"type ="text" /> 102 </td></tr> 103 <tr><td>Point</td> 104 <td><input name = "point"type ="text" /> 105 </td></tr> Craps.html

  9. 106 <tr><td><input type ="button"value ="Roll Dice" 107 onclick = "play()" /></td></tr> 108 </table> 109 </form> 110 </body> 111 </html> Craps.htmlProgram Output

  10. To begin the program, variable x is initialized to 1. Function start changes the value of x to 5. Function functionA changes the value of x to 25. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.7: scoping.html --> 6 <!-- Local and Global Variables --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>A Scoping Example</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var x = 1; // global variable 15 16 function start() 17 { 18 var x = 5; // variable local to function start 19 20 document.writeln( "local x in start is " + x ); 21 22 functionA(); // functionA has local x 23 functionB(); // functionB uses global variable x 24 functionA(); // functionA reinitializes local x 25 functionB(); // global variable x retains its value 26 27 document.writeln( 28 "<p>local x in start is " + x + "</p>" ); 29 } 30 31 function functionA() 32 { 33 var x = 25; // initialized each time 34 //functionA is called Scoping.html

  11. The value of x is incremented. Function functionB multiplies the value of x by 10. 35 36 document.writeln( "<p>local x in functionA is " + 37 x + " after entering functionA" ); 38 ++x; 39 document.writeln( "<br />local x in functionA is " + 40 x + " before exiting functionA" + "</p>" ); 41 } 42 43 function functionB() 44 { 45 document.writeln( "<p>global variable x is " + x + 46 " on entering functionB" ); 47 x *= 10; 48 document.writeln( "<br />global variable x is " + 49 x + " on exiting functionB" + "</p>" ); 50 } 51 // --> 52 </script> 53 54 </head> 55 <body onload = "start()"> 56 <noscript> 57 <p>This page requires Javascript to display properly</p> 58 </noscript> 59 </body> 60 </html> Scoping.html

  12. Program Output

  13. 10.9 JavaScript Global Functions

  14. 10.9 JavaScript Global Functions

  15. 10.10 Recursion Final value = 120 5! 5! 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! 1 returned 1 1 (a) Procession of recursive calls. (b) Values returned from each recursive call. Fig. 10.9 Recursive evaluation of 5!.

  16. Calling function factorial and passing it the value of i. Variable number gets the value of variable i. Call to function factorial and passing it 1 less than the current value of number. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4<!-- Fig. 10.10: FactorialTest.html --> 5<!-- Recursive factorial example --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Recursive Factorial Function</title> 10 11 <script language = "javascript"> 12 document.writeln( "<h1>Factorials of 1 to 10</h1>" ); 13 document.writeln( 14"<table border = '1' width = '100%'>" ); 15 16for ( var i = 0; i <= 10; i++ ) 17 document.writeln( "<tr><td>" + i + "!</td><td>" + 18 factorial( i ) + "</td></tr>" ); 19 20 document.writeln( "</table>" ); 21 22 // Recursive definition of function factorial 23function factorial( number ) 24 { 25if ( number <= 1 ) // base case 26return1; 27else 28return number * factorial( number - 1 ); 29 } 30 </script> 31 </head><body> 32 <noscript> 33 <p>This page requires Javascript to display properly</p> 34 </noscript> 35 </body> 36</html> FactorialTest.html

  17. Program Output

  18. 10.11 Example Using Recursion: Fibonacci Series Fig. 10.12 Set of recursive calls to function fibonacci.

  19. Convert from a string to an integer the value the user typed into the number text field. Display the number the user entered in the status bar. Display the result of the calculation in the result text field. The status bar displays a message that the call to function fibonacci is complete. Test for base case (n equal to 1 or 0). Two recursive calls are made if n is greater than 1. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4<!-- Fig. 10.11: FibonacciTest.html --> 5<!-- Recursive Fibonacci example --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Recursive Fibonacci Function</title> 10 11 <script language ="javascript"> 12 13 // Event handler for button XHTML component in myForm 14function getFibonacciValue() 15 { 16var value = parseInt( 17 document.myForm.number.value ); 18 window.status = 19"Calculating Fibonacci number for " + value; 20 document.myForm.result.value = fibonacci( value ); 21 window.status = "Done calculating Fibonacci number"; 22 } 23 24 // Recursive definition of function fibonacci 25 function fibonacci( n ) 26 { 27if ( n == 0 || n == 1 ) // base case 28return n; 29else 30return fibonacci( n - 1 ) + fibonacci( n - 2 ); 31 } 32 </script> 33 </head> 34 FibonacciTest.html

  20. 35 <body> 36 <form id ="myForm"> 37<table border = "1"> 38<tr><td>Enter an integer</td> 39 <td><input name ="number"type = "text"></td> 40 <td><input type ="button"value ="Calculate" 41onclick ="getFibonacciValue()"</tr> 42<tr><td>Fibonacci value</td> 43 <td><input name ="result"type ="text"></td></tr> 44 </table> 45 </form></body> 46</html> FibonacciTest.htmlProgram Output

  21. Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays 11.4 Examples Using Arrays 11.5 References and Reference Parameters 11.6 Passing Arrays to Functions 11.7 Sorting Arrays 11.8 Searching Arrays: Linear Search and Binary Search 11.9 Multiple-Subscripted Arrays 11.10 JavaScript Internet and World Wide Web Resources

  22. 11.2 Arrays c[ 0 ] -45 Name of array (Note that all elements of c[ 1 ] 6 this array have the c same name, ) c[ 2 ] 0 c[ 3 ] 72 c[ 4 ] 1543 c[ 5 ] -89 c[ 6 ] 0 c[ 7 ] 62 c[ 8 ] -3 c[ 9 ] 1 Position number (index or subscript) of the c[ 10 ] 6453 c element within array c[ 11 ] 78 Fig. 11.1 A 12-element array.

  23. Arrayn1 has five elements. Arrayn2 is an empty array. The for loop initializes the elements in n1 to their subscript numbers (0 to 4). The for loop adds five elements to Array n2 and initialize each element to its subscript number (0 to 4). Each function displays the contents of its respective Array in an XHTML table. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.3: InitArray.html --> 6 <!-- Initializing an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Initializing an Array</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 // this function is called when the <body> element's 15 // onload event occurs 16 function initializeArrays() 17 { 18 var n1 = new Array( 5 ); // allocate 5-element Array 19 var n2 = new Array(); // allocate empty Array 20 21 // assign values to each element of Array n1 22 for ( var i = 0; i < n1.length; ++i ) 23 n1[ i ] = i; 24 25 // create and initialize five-elements in Array n2 26 for ( i = 0; i < 5; ++i ) 27 n2[ i ] = i; 28 29 outputArray( "Array n1 contains", n1 ); 30 outputArray( "Array n2 contains", n2 ); 31 } 32 InitArray.html

  24. The second time function ouputArray is called, variable header gets the value of “Array n2 contains” and variable theArray gets the value of n2. The first time function ouputArray is called, variable header gets the value of “Array n1 contains” and variable theArray gets the value of n1. 33 // output "header" followed by a two-column table 34 // containing subscripts and elements of "theArray" 35 function outputArray( header, theArray ) 36 { 37 document.writeln( "<h2>" + header + "</h2>" ); 38 document.writeln( "<table border = \"1\" width =" + 39 "\"100%\">" ); 40 41 document.writeln( "<thead><th width = \"100\"" + 42 "align = \"left\">Subscript</th>" + 43 "<th align = \"left\">Value</th></thead><tbody>" ); 44 45 for ( var i = 0; i < theArray.length; i++ ) 46 document.writeln( "<tr><td>" + i + "</td><td>" + 47 theArray[ i ] + "</td></tr>" ); 48 49 document.writeln( "</tbody></table>" ); 50 } 51 // --> 52 </script> 53 54 </head><body onload ="initializeArrays()"> 55 <noscript> 56 <p>This page requires Javascript to display properly</p> 57 </noscript> 58</body> 59 </html> InitArray.html

  25. Program Output

  26. Arrayintegers1 is initialized using an initializer list. Two values are not supplied for integer2, which will be displayed as undefined. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.4: InitArray2.html --> 6 <!-- Initializing an Array with a Declaration --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Initializing an Array with a Declaration</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 function start() 15 { 16 // Initializer list specifies number of elements and 17 // value for each element. 18 var colors = new Array( "cyan", "magenta", 19 "yellow", "black" ); 20 var integers1 = [ 2, 4, 6, 8 ]; 21 var integers2 = [ 2, , , 8 ]; 22 23 outputArray( "Array colors contains", colors ); 24 outputArray( "Array integers1 contains", integers1 ); 25 outputArray( "Array integers2 contains", integers2 ); 26 } 27 InitArray2.html

  27. 28 // output "header" followed by a two-column table 29 // containing subscripts and elements of "theArray" 30 function outputArray( header, theArray ) 31 { 32 document.writeln( "<h2>" + header + "</h2>" ); 33 document.writeln( "<table border = \"1\"" + 34 "width = \"100%\">" ); 35 document.writeln( "<thead><th width = \"100\" " + 36 "align = \"left\">Subscript</th>" + 37 "<th align = \"left\">Value</th></thead><tbody>" ); 38 39 for ( var i = 0; i < theArray.length; i++ ) 40 document.writeln( "<tr><td>" + i + "</td><td>" + 41 theArray[ i ] + "</td></tr>" ); 42 43 document.writeln( "</tbody></table>" ); 44 } 45 // --> 46 </script> 47 48 </head><body onload ="start()"> 49 <noscript> 50 <p>This page requires Javascript to display properly</p> 51 </noscript> 52</body> 53 </html> InitArray2.html

  28. Program Output

  29. The for loop sums the values contained in the 10-element integer array called theArray. Variable element is assigned a subscript in the range of 0 up to, but not including, theArray.length. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.5: SumArray.html --> 6 <!-- Summing Elements of an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Sum the Elements of an Array</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 function start() 15 { 16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; 17 var total1 = 0, total2 = 0; 18 19 for ( var i = 0; i < theArray.length; i++ ) 20 total1 += theArray[ i ]; 21 22 document.writeln( "Total using subscripts: " + total1 ); 23 24 for ( var element in theArray ) 25 total2 += theArray[ element ]; 26 27 document.writeln( "<br />Total using for/in: " + 28 total2 ); 29 } 30 // --> 31 </script> 32 33 </head><body onload ="start()"> SumArray.html

  30. 34 <noscript> 35 <p>This page requires Javascript to display properly</p> 36 </noscript> 37</body> 38 </html> SumArray.html

  31. Program Output

  32. The first call to function outputArray displays the contents of the Array a before it is modified. Function modifyArray multiplies each element by 2. The value of a[3] is output to show its contents before it is modified. Again, function outputArray is called to show that the contents of Arraya have been modified. Function modifyElement multiplies the contents of a[ 3 ] by 2. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.7: PassArray.html --> 6 <!-- Passing Arrays --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Passing Arrays and Individual Array 11 Elements to Functions</title> 12 13 <script type = "text/javascript"> 14 <!-- 15 function start() 16 { 17 var a = [ 1, 2, 3, 4, 5 ]; 18 19 document.writeln( "<h2>Effects of passing entire " + 20 "array call-by-reference</h2>" ); 21 outputArray( 22 "The values of the original array are: ", a ); 23 24 modifyArray( a ); // array a passed call-by-reference 25 26 outputArray( 27 "The values of the modified array are: ", a ); 28 29 document.writeln( "<h2>Effects of passing array " + 30 "element call-by-value</h2>" + 31 "a[3] before modifyElement: " + a[ 3 ] ); 32 33 modifyElement( a[ 3 ] ); 34 PassArray.html

  33. Method join takes as its argument a string containing a separator that should be used to separate the elements of the array in the string that is returned. Multiply each element in theArray by 2. 35 document.writeln( 36 "<br />a[3] after modifyElement: " + a[ 3 ] ); 37 } 38 39 // outputs "header" followed by the contents of "theArray" 40 function outputArray( header, theArray ) 41 { 42 document.writeln( 43 header + theArray.join( " " ) + "<br />" ); 44 } 45 46 // function that modifies the elements of an array 47 function modifyArray( theArray ) 48 { 49 for ( var j in theArray ) 50 theArray[ j ] *= 2; 51 } 52 53 // function that attempts to modify the value passed 54 function modifyElement( e ) 55 { 56 e *= 2; 57 document.writeln( "<br />value in modifyElement: " + e ); 58 } 59 // --> 60 </script> 61 62 </head><body onload ="start()"> 63 <noscript> 64 <p>This page requires Javascript to display properly</p> 65 </noscript> 66</body> 67 </html> PassArray.html

  34. Program Output

  35. Method sort takes as its optional argument the name of a function that compares two arguments and returns a value of –1, 0 or 1. Function compareIntegers calculates the difference between the integer values of its arguments. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.8: sort.html --> 6 <!-- Sorting an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Sorting an Array with Array Method sort</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 17 18 document.writeln( "<h1>Sorting an Array</h1>" ); 19 outputArray( "Data items in original order: ", a ); 20 a.sort( compareIntegers ); // sort the array 21 outputArray( "Data items in ascending order: ", a ); 22 } 23 24 // outputs "header" followed by the contents of "theArray" 25 function outputArray( header, theArray ) 26 { 27 document.writeln( "<p>" + header + 28 theArray.join( " " ) + "</p>" ); 29 } 30 Sort.html

  36. 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // --> 37 </script> 38 39 </head><body onload = "start()"> 40 <noscript> 41 <p>This page requires Javascript to display properly</p> 42 </noscript> 43 </body> 44 </html> Sort.htmlProgram Output

  37. Arraya is initiated with 100 elements. Array a is populated with the integers 0 to 198. Get value of search key from the input field in the XHTML form. Calling function linearSearch and passing it the Arraya and the value of variable searchKey as an integer. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.9: LinearSearch.html --> 6 <!-- Linear Search of an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Linear Search of an Array</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var a = new Array( 100 ); // create an Array 15 16 // fill Array with even integer values from 0 to 198 17 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; 19 20 // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; 24 25 // Array a is passed to linearSearch even though it 26 // is a global variable. Normally an array will 27 // be passed to a method for searching. 28 var element = linearSearch( a, parseInt( searchKey ) ); 29 30 if ( element != -1 ) 31 searchForm.result.value = 32 "Found value in element " + element; 33 else 34 searchForm.result.value = "Value not found"; 35 } LinearSearch.html

  38. Function linearSearch compares each each element with a search key. Variable theArray gets the value of Array a and variable key gets the value of variable searchKey. 36 37 // Search "theArray" for the specified "key" value 38 function linearSearch( theArray, key ) 39 { 40 for ( var n = 0; n < theArray.length; ++n ) 41 if ( theArray[ n ] == key ) 42 return n; 43 44 return-1; 45 } 46 // --> 47 </script> 48 49 </head> 50 51 <body> 52 <form id = "searchForm" action = ""> 53 <p>Enter integer search key<br /> 54 <input name ="inputVal"type ="text" /> 55 <input name ="search"type ="button"value ="Search" 56 onclick ="buttonPressed()" /><br /></p> 57 58 <p>Result<br /> 59 <input name ="result"type ="text"size ="30" /></p> 60 </form> 61 </body> 62 </html> LinearSearch.html

  39. Program Output

  40. 11.9 Multiple-Subscripted Arrays Fig. 11.11 Double-subscripted array with three rows and four columns.

  41. Arrayarray1 provides six initializers in two sublists. Arrayarray2 provides six initializers in three sublists. Function outputArray displays each array’s elements in a Web page. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.12: InitArray3.html --> 6 <!-- Initializing Multidimensional Arrays --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Initializing Multidimensional Arrays</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 function start() 15 { 16 var array1 = [ [ 1, 2, 3 ], // first row 17 [ 4, 5, 6 ] ]; // second row 18 var array2 = [ [ 1, 2 ], // first row 19 [ 3 ], // second row 20 [ 4, 5, 6 ] ]; // third row 21 22 outputArray( "Values in array1 by row", array1 ); 23 outputArray( "Values in array2 by row", array2 ); 24 } 25 26 function outputArray( header, theArray ) 27 { 28 document.writeln( "<h2>" + header + "</h2><tt>" ); 29 InitArray3.html

  42. Referencing the multidimensional array theArray. 30 for ( var i in theArray ) { 31 32 for ( var j in theArray[ i ] ) 33 document.write( theArray[ i ][ j ] + " " ); 34 35 document.writeln( "<br />" ); 36 } 37 38 document.writeln( "</tt>" ); 39 } 40 // --> 41 </script> 42 43 </head><body onload = "start()"> 44 <noscript> 45 <p>This page requires Javascript to display properly</p> 46 </noscript> 47</body> 48 </html> InitArray3.htmlProgram Output

  43. Chapter 12 - JavaScript: Objects Outline 12.1 Introduction 12.2 Thinking About Objects 12.3 Math Object 12.4 String Object 12.4.1 Fundamentals of Characters and Strings 12.4.2 Methods of the String Object 12.4.3 Character Processing Methods 12.4.4 Searching Methods 12.4.5 Splitting Strings and Obtaining Substrings 12.4.6 XHTML Markup Methods 12.5 Date Object 12.6 Boolean and Number Objects 12.7 JavaScript Internet and World Wide Web Resources

  44. 12.3 Math Object

  45. 12.3 Math Object

  46. 12.4.2 Methods of the String Object

  47. 12.4.2 Methods of the String Object

  48. Method charAt returns a string containing the character at the specified index (0 in this example). Method charCodeAt returns the Unicode value of the character at the specified index (0 in this example). Method fromCharCode takes a comma-separated list of Unicode values and builds a string containing the character representation of those Unicode values. Methods toLowerCase and toUpperCase display versions of String s2 in all lowercase and all upper case letters, respectively. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 12.4: CharacterProcessing.html --> 6 <!-- Character Processing Methods --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Character Processing Methods</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var s = "ZEBRA"; 15 var s2 = "AbCdEfG"; 16 17 document.writeln( "<p>Character at index 0 in '" + 18 s + "' is " + s.charAt( 0 ) ); 19 document.writeln( "<br />Character code at index 0 in '" 20 + s + "' is " + s.charCodeAt( 0 ) + "</p>" ); 21 22 document.writeln( "<p>'" + 23 String.fromCharCode( 87, 79, 82, 68 ) + 24 "' contains character codes 87, 79, 82 and 68</p>" ) 25 26 document.writeln( "<p>'" + s2 + "' in lowercase is '" + 27 s2.toLowerCase() + "'" ); 28 document.writeln( "<br />'" + s2 + "' in uppercase is '" 29 + s2.toUpperCase() + "'</p>" ); 30 // --> 31 </script> 32 33 </head><body> CharacterProcessing.html

  49. 34 <noscript> 35 <p>This page requires Javascript to display properly</p> 36 </noscript> 37</body> 38 </html> CharacterProcessing.html

  50. Program Output

More Related