Documente Academic
Documente Profesional
Documente Cultură
JavaScript: Functions
Outline
10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 Introduction ProgramModulesinJavaScript ProgrammerDefinedFunctions FunctionDefinitions RandomNumberGeneration Example:GameofChance AnotherExample:RandomImageGenerator ScopeRules JavaScriptGlobalFunctions Recursion Recursionvs.Iteration WebResources
boss
worker1
worker2
worker3
worker4
worker5
Parameters
Also local variables
Promotes reusability
Keep short Name clearly
Function name any valid identifier Parameter list names of variables that will receive arguments Must have same number as function call May be empty Declarations and statements
Function body (block of code)
2004 Prentice Hall, Inc. All rights reserved.
10
No return statement same as return; Not returning a value when expected is an error
11
Pass each number as argument to square return value of argument multiplied by itself Display result
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.2: SquareInt.html --> <!-- Square function <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Programmer-Defined square Function</title> <script type = "text/javascript"> <!-document.writeln( "<h1>Square the numbers from 1 to 10</h1>" ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + "<br />" ); -->
Outline
SquareInt.html (1 of 2)
12
11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 30 31 32 33
// The following square function's body is executed // only when the functionVariable is explicitly y gets called. the value // square function definition function square( y ) { return y * y; } // --> </script> </head><body></body>
of variable x.
Outline
SquareInt.html (2 of 2)
13
The return statement passes the value of y * y back to the calling function.
34 </html>
14
15
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.3: maximum.html --> <!-- Maximum function <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Finding the Maximum of Three Values</title> -->
Outline
Maximum.html (1 of 2)
16
11 12 13 14 15 16 17 18 19 20 21 22 23 <!-var input1 =
window.prompt( "Enter first number", "0" ); var input2 = window.prompt( "Enter second number", "0" ); var input3 = window.prompt( "Enter third number", "0" ); var value1 = parseFloat( input1 ); var value2 = parseFloat( input2 ); var value3 = parseFloat( input3 );
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> } // --> </script> function maximum( x, y, z ) { return Math.max( x, Math.max( Variables y, z ) ); x, document.writeln( "First number: " + value1 + "<br />Second number: " + value2 + "<br />Third number: " + value3 "<br />Maximum is: " + maxValue var maxValue = maximum( value1, value2, value3 );
Outline
17
Call function maximum and pass it the value of variables value1, value2 and value3.Maximum.html + (2 of 2) ); Method max returns the larger of the two integers passed to it.
y and z get the value of variables value1, value2 and value3, respectively.
44 </html>
18
19
20
var randomValue = Math.random(); Floating point value between 0 and 1 Adjust range by scaling and shifting Math.floor
Always round down
Math.floor( 1 + Math.random() * 6 )
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.4: RandomInt.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Shifted and Scaled Random Integers</title> <script type = "text/javascript"> <!-var value; document.writeln( "<table border = \"1\" width = \"50%\">" ); document.writeln( "<caption>Random Numbers</caption><tr>" ); --> <!-- Demonstrating the Random method -->
Outline
RandomInt.html (1 of 2)
21
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
for ( var i = 1; i <= 20; i++ ) { value = Math.floor( 1 + Math.random() * 6 ); document.writeln( "<td>" + value + "</td>" ); // write end and start <tr> tags when
Method floor rounds the number Outline generated by method random down. RandomInt.html (2 of 2) Each cell is populated with a random number generated by method random.
22
The for loop if creates ( i % 5 20 == 0 && i table cells (4 rows x5 document.writeln( columns). }
document.writeln( "</tr></table>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>
39 </html>
23
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.5: RollDie.html --> <!-- Rolling a Six-Sided Die --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Roll a Six-Sided Die 6000 Times</title> <script type = "text/javascript"> <!-var frequency1 = 0, frequency2 =
Outline
RollDie.html (1 of 3)
24
11 12 13 14 15 16 17 18 19 20 21 // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 );
This expression uses method random to generate a random number between 1 and 6. 0,
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 }
switch ( face ) { case 1: ++frequency1; break; case 2: ++frequency2; break; case 3: ++frequency3; break; case 4: ++frequency4; break; case 5: ++frequency5; break; case 6: ++frequency6; break; }
Outline
When the controlling expression, face, matches a case label, the respective frequency variable is incremented. RollDie.html (2 of 3)
25
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>
Outline The results of rolling the die 600 times are displayed in a table. RollDie.html
(3 of 3)
26
67 </html>
27
28
29
Constants
Variable that cannot be modified Part of many languages, not supported in JavaScript
Name constant variables with all capital letters
30
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 10.6: Craps.html --> <!-- Craps Program <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Program that Simulates the Game of Craps</title> <script type = "text/javascript"> <!-// variables used to test the state of the game var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; // other variables used in program var firstRoll = true, sumOfDice = 0, // true if first roll // sum of the dice -->
Outline
Craps.html (1 of 5)
31
11 12 13 14 15 16 17 18 19 20 21 22
myPoint = 0, // point if no win/loss on first roll gameStatus = CONTINUE_ROLLING; // game not over yet
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// process one roll of the dice function play() { if ( firstRoll ) { sumOfDice = rollDice(); switch ( sumOfDice ) { case 7: case 11: gameStatus = WON; // clear point field break; case 2: case 3: case 12: // lose on first roll gameStatus = LOST; // clear point field document.craps.point.value break; default: myPoint = sumOfDice; document.craps.point.value = myPoint; firstRoll = false; } } // // first roll of the dice
Outline
If the value of firstRoll is true, then function rollDice is called. Craps.html (2 of 5) If function rollDice returns a value of 7 or 11, the player wins and the break // win on first roll statement causes program control proceeds to the first line after the switch structure.
32
document.craps.point.value = "";
If function rollDice returns a 2, 3 or 12, the player loses and the break statement causes = ""; control to proceed to first line after the switch structure. remember point
gameStatus = CONTINUE_ROLLING;
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 }
else { sumOfDice = rollDice(); if ( sumOfDice == myPoint ) // win by making point gameStatus = WON; else if ( sumOfDice == 7 ) gameStatus = LOST; } if ( gameStatus == CONTINUE_ROLLING ) window.status = "Roll again"; else { if ( gameStatus == WON ) //
Outline
If the value of firstRoll is false,Craps.html function rollDice is called to see if(3 the of 5) point been 7 reached. lose by has rolling
33
If the value returned by function rollDice the value of variable myPoint, the player window.status = "Player wins. " equals + wins because the point has been reached. "Click Roll Dice to play again.";
window.status = "Player loses. " + "Click Roll Dice to play again.";
else
firstRoll = true; }
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
// roll the dice function rollDice() { var die1, die2, workSum; die1 = Math.floor( 1
Outline
Function rollDice is called to simulate + the Math.random() * 6 dice ); on the craps table. rolling of two Craps.html (4 of 5)
34
die2 = Math.floor( 1 + Math.random() * 6 ); workSum = die1 + die2; document.craps.firstDie.value = die1; Methods document.craps.secondDie.value = die2; generate document.craps.sum.value = workSum; return workSum; } // --> </script> </head>
Referencing the names of form elements in the XHTML document, the values of the dice are placed in their respective form fields.
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
<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> <tr><td><input type = "button" value = "Roll Dice" onclick = "play()" /></td></tr> </table> </form> </body>
Outline
Craps.html (5 of 5)
35
111 </html>
36
37
38
39
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- Fig. 10.7: RandomPicture.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Random Image --> <!-- Randomly displays one of 7 images -->
Outline
40
RandomPicture.html (1 of 1)
Inserting a random number into the images src property with document.write and Math.random Generator</title>
11 12 13 14 15 16 17 18 19 20 21 22 23 24 <body> <p>Click Refresh (or Reload) to run the script again</p> </body> </head> <script type = "text/javascript"> <!-document.write ( "<img src = \"" + Math.floor( 1 + Math.random() * 7 ) + ".gif\" width = \"105\" height = \"100\" />" ); // --> </script>
25 </html>
41
42
43
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.8: scoping.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Scoping Example</title> <script type = "text/javascript"> <!-var x = 1; // global variable --> <!-- Local and Global Variables -->
Outline
Scoping.html (1 of 3)
44
document.writeln( "local x in start is " + x ); functionA(); // functionA has local x functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 } ++x; document.writeln( "<br />local x in functionA is " + x + " before exiting functionA" + "</p>" ); document.writeln( "<p>local x in functionA is " + x + " after entering functionA" ); function functionA() { var x = 25; // initialized each time // functionA is called } document.writeln( "<p>local x in start is " + x + "</p>" );
Outline
Scoping.html (2 of 3)
45
43 44 45 46 47 48 49 50 51 52 53 54 55
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" } // --> </script> </head> <body onload = "start()"></body> + "</p>" );
Outline
Scoping.html (3 of 3)
46
56 </html>
47
48
49
eval
isFinite
isNaN
Description This function takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set (see Appendix D, ASCII Character Set) are encoded in a hexadecimal format (see Appendix E, Number Systems) that can be represented on all platforms. This function takes a string argument representing JavaScript code to execute. The JavaScript interpreter evaluates the code and executes it when the eval function is called. This function allows JavaScript code to be stored as strings and executed dynamically. This function takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise, the function returns false. This function takes a numeric argument and returns true if the value of the argument is not a number; otherwise, it returns false. The function is commonly used with the return value of parseInt or parseFloat to determine whether the result is a proper numeric value.
50
parseInt
unescape
Description This function takes a string argument and attempts to convert the beginning of the string into a floatingpoint value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and parseFloat( "123.45abc" ) returns the value 123.45). This function takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt( "123abc" ) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format. See see Appendex E, Number Systems, for more information on binary, octal and hexadecimal numbers. This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded.
51
52
53
10.10 Recursion
1 2 3 4 5 6 7 8 9 10
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 10.11: FactorialTest.html --> <!-- Recursive factorial example <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Recursive Factorial Function</title> <script language = "javascript"> document.writeln( -->
Outline
FactorialTest.html (1 of 2)
54
11 12 13 14 15 16 17 18 19 20 21 22 document.writeln( "</table>" ); for ( var i = 0; i <= 10; i++ ) document.writeln( "<tr><td>" + i + "!</td><td>" + factorial( i ) + "</td></tr>" ); document.writeln( "<h1>Factorials of 1 to 10</h1>" ); "<table border = '1' width = '100%'>" );
23 24 25 26 27 28 29 30 31 32
// Recursive definition of function factorial function factorial( number ) { if ( number <= 1 ) return 1; else } </script> </head><body></body>
Variable number gets the value of variable i. Outline to function factorial and passing it 1 less than the current value of number . FactorialTest.html (2 of 2)
55
33 </html>
56
10.10 Recursion
Fig. 10.11 Factorial calculation with a recursive function.
57
Recursion
Repeats through function calls Terminates when base case reached Slower due to function call overhead
Each call generates new copy of local variables
Easy to read and debug when modeling problem with naturally recursive solution
58
12 13