Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript: Functions

Similar presentations


Presentation on theme: "JavaScript: Functions"— Presentation transcript:

1 JavaScript: Functions
Outline 1 Introduction 2 Program Modules in JavaScript 3 Programmer-Defined Functions 4 Function Definitions 5 Random-Number Generation 6 Example: Game of Chance 7 Duration of Identifiers 8 Scope Rules 9 JavaScript Global Functions 10 Recursion 11 Example Using Recursion: Fibonacci Series 12 Recursion vs. Iteration 13 JavaScript Internet and World Wide Web Resources

2 2 Program Modules in JavaScript
main worker1 worker2 worker3 worker4 worker5 Fig. 1 Hierarchical boss-function/worker-function relationship.

3 Calling function square and passing it the value of x.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.2: SquareInt.html --> 6 <!-- Square function > 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Programmer-Defined square Function</title> 11 <script type = "text/javascript"> <!-- document.writeln( "<h1>Square the numbers from 1 to 10</h1>" ); 16 // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + "<br />" ); 21 // The following square function's body is executed // only when the function is explicitly called. 24 // square function definition function square( y ) { return y * y; } // --> </script> 32 </head><body></body> 34 </html> SquareInt.html Calling function square and passing it the value of x. Variable y gets the value of variable x. The return statement passes the value of y * y back to the calling function. 32. 33 34 SquareInt.html. Calling function square and passing it the value of x. Variable y gets the value of variable x. The return statement passes the value of y * y back to the calling function.", "width": "800" }

4 Program Output

5 Prompt for the user to input three integers.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.3: maximum.html --> 6 <!-- Maximum function > 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Finding the Maximum of Three Values</title> 11 <script type = "text/javascript"> <!-- var input1 = window.prompt( "Enter first number", "0" ); var input2 = window.prompt( "Enter second number", "0" ); var input3 = window.prompt( "Enter third number", "0" ); 20 var value1 = parseFloat( input1 ); var value2 = parseFloat( input2 ); var value3 = parseFloat( input3 ); 24 var maxValue = maximum( value1, value2, value3 ); 26 document.writeln( "First number: " + value1 + "<br />Second number: " + value2 + "<br />Third number: " + value3 + "<br />Maximum is: " + maxValue ); 31 // maximum method definition (called from line 25) function maximum( x, y, z ) { return Math.max( x, Math.max( y, z ) ); Maximum.html 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.

6 Maximum.html Program Output
} // --> </script> 39 </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> 44 </html> Maximum.html Program Output 39. 40 41 42

Click Refresh (or Reload) to run the script again

43 44 Maximum.html Program Output.", "width": "800" }

7 Program Output

8 The for loop creates 4 rows with 5 cells of a table.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.4: RandomInt.html > 6 <!-- Demonstrating the Random method --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Shifted and Scaled Random Integers</title> 11 <script type = "text/javascript"> <!-- var value; 15 document.writeln( "<table border = \"1\" width = \"50%\">" ); document.writeln( "<caption>Random Numbers</caption><tr>" ); 20 for ( var i = 1; i <= 20; i++ ) { value = Math.floor( 1 + Math.random() * 6 ); document.writeln( "<td>" + value + "</td>" ); 24 // write end and start <tr> tags when // i is a multiple of 5 and not 20 if ( i % 5 == 0 && i != 20 ) document.writeln( "</tr><tr>" ); } 30 document.writeln( "</tr></table>" ); // --> </script> 34 </head> RandomInt.html 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. 34. 35 RandomInt.html. 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.", "width": "800" }

9 RandomInt.html Program Output
<body> <p>Click Refresh (or Reload) to run the script again</p> </body> 39 </html> RandomInt.html Program Output

10 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.5: RollDie.html --> 6 <!-- Rolling a Six-Sided Die --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Roll a Six-Sided Die 6000 Times</title> 11 <script type = "text/javascript"> <!-- var frequency1 = 0, frequency2 = 0, frequency3 = 0, frequency4 = 0, frequency5 = 0, frequency6 = 0, face; 17 // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); 21 switch ( face ) { case 1: frequency1; break; case 2: frequency2; break; case 3: frequency3; break; case 4: frequency4; break; case 5: RollDie.html This expression uses method random to generate a random number between 1 and 6. When the controlling expression, face, matches a case label, the respective frequency variable is incremented.

11 frequency5; break; case 6: frequency6; break; } } 43 document.writeln( "<table border = \"1\"" + "width = \"50%\">" ); document.writeln( "<thead><th>Face</th>" + "<th>Frequency<th></thead>" ); document.writeln( "<tbody><tr><td>1</td><td>" + frequency1 + "</td></tr>" ); document.writeln( "<tr><td>2</td><td>" + frequency2 + "</td></tr>" ); document.writeln( "<tr><td>3</td><td>" + frequency3 + "</td></tr>" ); document.writeln( "<tr><td>4</td><td>" + frequency4 + "</td></tr>" ); document.writeln( "<tr><td>5</td><td>" + frequency5 + "</td></tr>" ); document.writeln( "<tr><td>6</td><td>" + frequency6 + "</td></tr></tbody></table>" ); // --> </script> 62 </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> 67 </html> RollDie.html The results of the dice being rolled 600 times are displayed in a table. 62. 63 64 65

Click Refresh (or Reload) to run the script again

66 67 RollDie.html. The results of the dice being rolled 600 times are displayed in a table.", "width": "800" }

12 Program Output

13 If the value of firstRoll is true, then function rollDice is called.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <!-- Fig. 10.6: Craps.html --> 6 <!-- Craps Program > 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Program that Simulates the Game of Craps</title> 11 <script type = "text/javascript"> <!-- // variables used to test the state of the game var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 16 // other variables used in program var firstRoll = true, // true if first roll sumOfDice = 0, // sum of the dice myPoint = 0, // point if no win/loss on first roll gameStatus = CONTINUE_ROLLING; // game not over yet 22 // process one roll of the dice function play() { if ( firstRoll ) { // first roll of the dice sumOfDice = rollDice(); 28 switch ( sumOfDice ) { case 7: case 11: // win on first roll gameStatus = WON; // clear point field document.craps.point.value = ""; break; case 2: case 3: case 12: // lose on first roll Craps.html 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.

14 gameStatus = LOST; // clear point field document.craps.point.value = ""; break; default: // remember point gameStatus = CONTINUE_ROLLING; myPoint = sumOfDice; document.craps.point.value = myPoint; firstRoll = false; } } else { sumOfDice = rollDice(); 49 if ( sumOfDice == myPoint ) // win by making point gameStatus = WON; else if ( sumOfDice == 7 ) // lose by rolling 7 gameStatus = LOST; } 56 if ( gameStatus == CONTINUE_ROLLING ) window.status = "Roll again"; else { if ( gameStatus == WON ) window.status = "Player wins. " + "Click Roll Dice to play again."; else window.status = "Player loses. " + "Click Roll Dice to play again."; 66 firstRoll = true; } } 70 Craps.html 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.

15 // roll the dice function rollDice() { var die1, die2, workSum; 75 die1 = Math.floor( 1 + Math.random() * 6 ); die2 = Math.floor( 1 + Math.random() * 6 ); workSum = die1 + die2; 79 document.craps.firstDie.value = die1; document.craps.secondDie.value = die2; document.craps.sum.value = workSum; 83 return workSum; } // --> </script> 88 </head> <body> <form name = "craps" action = ""> <table border = "1"> <caption>Craps</caption> <tr><td>Die 1</td> <td><input name = "firstDie" type = "text" /> </td></tr> <tr><td>Die 2</td> <td><input name = "secondDie" type = "text" /> </td></tr> <tr><td>Sum</td> <td><input name = "sum" type = "text" /> </td></tr> <tr><td>Point</td> <td><input name = "point" type = "text" /> </td></tr> Function rollDice is called to simulate the rolling of two dice on the craps table. Craps.html 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. 88. 89 90 91

92 93 94 95 97 98 100 101 103 104 Function rollDice is called to simulate the rolling of two dice on the craps table. Craps.html. 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.", "width": "800" }

16 Craps.html Program Output
<tr><td><input type = "button" value = "Roll Dice" onclick = "play()" /></td></tr> </table> </form> </body> 111 </html> Craps.html Program Output

17 Program Output

18 Program Output

19 To begin the program, variable x is initialized to 1.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.7: scoping.html --> 6 <!-- Local and Global Variables --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Scoping Example</title> 11 <script type = "text/javascript"> <!-- var x = 1; // global variable 15 function start() { var x = 5; // variable local to function start 19 document.writeln( "local x in start is " + x ); 21 functionA(); // functionA has local x functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value 26 document.writeln( "<p>local x in start is " + x + "</p>" ); } 30 function functionA() { var x = 25; // initialized each time // functionA is called Scoping.html 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.

20 The value of x is incremented.
35 document.writeln( "<p>local x in functionA is " + x + " after entering functionA" ); x; document.writeln( "<br />local x in functionA is " + x + " before exiting functionA" + "</p>" ); } 42 function functionB() { document.writeln( "<p>global variable x is " + x + " on entering functionB" ); x *= 10; document.writeln( "<br />global variable x is " + x + " on exiting functionB" + "</p>" ); } // --> </script> 53 </head> <body onload = "start()"></body> 56 </html> Scoping.html The value of x is incremented. Function functionB multiplies the value of x by 10. 53. 54 55 56 Scoping.html. The value of x is incremented. Function functionB multiplies the value of x by 10.", "width": "800" }

21 Program Output

22 9 JavaScript Global Functions

23 9 JavaScript Global Functions

24 10 Recursion Final value = 120 Fig. 10.9 Recursive evaluation of 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 Recursive evaluation of 5!.

25 Calling function factorial and passing it the value of i.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 <!-- Fig : FactorialTest.html --> 5 <!-- Recursive factorial example --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Recursive Factorial Function</title> 10 <script language = "javascript"> document.writeln( "<h1>Factorials of 1 to 10</h1>" ); document.writeln( "<table border = '1' width = '100%'>" ); 15 for ( var i = 0; i <= 10; i++ ) document.writeln( "<tr><td>" + i + "!</td><td>" + factorial( i ) + "</td></tr>" ); 19 document.writeln( "</table>" ); 21 // Recursive definition of function factorial function factorial( number ) { if ( number <= 1 ) // base case return 1; else return number * factorial( number - 1 ); } </script> </head><body></body> 32 </html> FactorialTest.html 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. 31 32 FactorialTest.html. 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.", "width": "800" }

26 Program Output

27 Display the number the user entered in the status bar.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 <!-- Fig : FibonacciTest.html --> 5 <!-- Recursive Fibonacci example --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Recursive Fibonacci Function</title> 10 <script language = "javascript"> 12 // Event handler for button XHTML component in myForm function getFibonacciValue() { var value = parseInt( document.myForm.number.value ); window.status = "Calculating Fibonacci number for " + value; document.myForm.result.value = fibonacci( value ); window.status = "Done calculating Fibonacci number"; } 23 // Recursive definition of function fibonacci function fibonacci( n ) { if ( n == 0 || n == 1 ) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } </script> </head> 34 FibonacciTest.html 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. 33 34. FibonacciTest.html. 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.", "width": "800" }

28 FibonacciTest.html Program Output
<body> <form name = "myForm"> <table border = "1"> <tr><td>Enter an integer</td> <td><input name = "number" type = "text"></td> <td><input type = "button" value = "Calculate" onclick = "getFibonacciValue()"</tr> <tr><td>Fibonacci value</td> <td><input name = "result" type = "text"></td></tr> </table> </form></body> 46 </html> FibonacciTest.html Program Output

29 Program Output

30 11 Example Using Recursion: Fibonacci Series
Fig Set of recursive calls to function fibonacci.

31 12 Recursion vs. Iteration


Download ppt "JavaScript: Functions"

Similar presentations


Ads by Google
Craps
Die 1 96
Die 2 99
Sum 102
Point 105