2001 prentice hall, inc. all rights reserved. 1 chapter 10 - javascript: functions outline 10.1...

51
2001 Prentice Hall, Inc. All rights reserved. 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

Upload: lora-holland

Post on 29-Dec-2015

216 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

1

Chapter 10 - JavaScript: Functions

Outline10.1 Introduction10.2 Program Modules in JavaScript10.3 Programmer-Defined Functions10.4 Function Definitions10.5 Random-Number Generation10.6 Example: Game of Chance10.7 Duration of Identifiers10.8 Scope Rules10.9 JavaScript Global Functions10.10 Recursion10.11 Example Using Recursion: Fibonacci Series10.12 Recursion vs. Iteration10.13 JavaScript Internet and World Wide Web Resources

Page 2: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

2

10.2 Program Modules in JavaScript

main

worker1 worker2 worker3

worker4 worker5

Fig. 10.1 Hierarchical boss-function/worker-function relationship.

Page 3: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline3

SquareInt.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "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">9 <head>10 <title>A Programmer-Defined square Function</title>11 12 <script type = "text/javascript">13 <!--14 document.writeln( 15 "<h1>Square the numbers from 1 to 10</h1>" );16 17 // square the numbers from 1 to 1018 for ( var x = 1; x <= 10; ++x ) 19 document.writeln( "The square of " + x + " is " + 20 square( x ) + "<br />" );21 22 // The following square function's body is executed 23 // only when the function is explicitly called.24 25 // square function definition 26 function square( y )27 {28 return y * y;29 }30 // -->31 </script>32 33 </head><body></body>34 </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.

Page 4: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline4

Program Output

Page 5: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline5

Maximum.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "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">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 ) );

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.

Page 6: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline6

Maximum.html

Program Output

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>

Page 7: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline7

Program Output

Page 8: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline8

RandomInt.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "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">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 when26 // i is a multiple of 5 and not 2027 if ( i % 5 == 0 && i != 20 )28 document.writeln( "</tr><tr>" );29 }30 31 document.writeln( "</tr></table>" );32 // -->33 </script>34 35 </head>

The for loop creates 4 rows with 5 cells of a table.

Each cell is populated with a random number generated by method random.

Method floor rounds the number generated by method random down.

Page 9: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline9

RandomInt.html

Program Output

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

Page 10: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline10

RollDie.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "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">9 <head>10 <title>Roll a Six-Sided Die 6000 Times</title> 11 12 <script type = "text/javascript">13 <!--14 var frequency1 = 0, frequency2 = 0,15 frequency3 = 0, frequency4 = 0,16 frequency5 = 0, frequency6 = 0, face;17 18 // summarize results19 for ( var roll = 1; roll <= 6000; ++roll ) {20 face = Math.floor( 1 + Math.random() * 6 );21 22 switch ( face ) {23 case 1:24 ++frequency1;25 break;26 case 2:27 ++frequency2;28 break;29 case 3:30 ++frequency3;31 break;32 case 4:33 ++frequency4;34 break;35 case 5:

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.

Page 11: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline11

RollDie.html

36 ++frequency5;37 break;38 case 6:39 ++frequency6;40 break;41 }42 }43 44 document.writeln( "<table border = \"1\"" + 45 "width = \"50%\">" );46 document.writeln( "<thead><th>Face</th>" +47 "<th>Frequency<th></thead>" );48 document.writeln( "<tbody><tr><td>1</td><td>" +49 frequency1 + "</td></tr>" );50 document.writeln( "<tr><td>2</td><td>" + frequency2 + 51 "</td></tr>" );52 document.writeln( "<tr><td>3</td><td>" + frequency3 + 53 "</td></tr>" );54 document.writeln( "<tr><td>4</td><td>" + frequency4 + 55 "</td></tr>" );56 document.writeln( "<tr><td>5</td><td>" + frequency5 + 57 "</td></tr>" );58 document.writeln( "<tr><td>6</td><td>" + frequency6 + 59 "</td></tr></tbody></table>" );60 // -->61 </script>62 63 </head>64 <body>65 <p>Click Refresh (or Reload) to run the script again</p>66 </body>67 </html>

The results of the dice being rolled 600 times are displayed in a table.

Page 12: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline12

Program Output

Page 13: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline13

Craps.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"3 "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">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 program18 var firstRoll = true, // true if first roll19 sumOfDice = 0, // sum of the dice20 myPoint = 0, // point if no win/loss on first roll21 gameStatus = CONTINUE_ROLLING; // game not over yet22 23 // process one roll of the dice24 function play()25 {26 if ( firstRoll ) { // first roll of the dice27 sumOfDice = rollDice(); 28 29 switch ( sumOfDice ) {30 case 7: case 11: // win on first roll31 gameStatus = WON;32 // clear point field33 document.craps.point.value = ""; 34 break;35 case 2: case 3: case 12: // lose on first roll

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.

Page 14: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline14

Craps.html

36 gameStatus = LOST;37 // clear point field38 document.craps.point.value = ""; 39 break;40 default: // remember point41 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 point51 gameStatus = WON;52 else53 if ( sumOfDice == 7 ) // lose by rolling 754 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

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.

Page 15: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline15

Craps.html

71 // roll the dice72 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 name = "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>

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.

Page 16: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline16

Craps.html

Program Output

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

A text XHTML GUI component

A button XHTML GUI component

Browser’s status bar

Page 17: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline17

Program Output

Page 18: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline18

Program Output

Page 19: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline19

Scoping.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "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">9 <head>10 <title>A Scoping Example</title>11 12 <script type = "text/javascript">13 <!--14 var x = 1; // global variable15 16 function start()17 {18 var x = 5; // variable local to function start19 20 document.writeln( "local x in start is " + x );21 22 functionA(); // functionA has local x23 functionB(); // functionB uses global variable x24 functionA(); // functionA reinitializes local x25 functionB(); // global variable x retains its value26 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

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.

Page 20: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline20

Scoping.html

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()"></body>56 </html>

The value of x is incremented.

Function functionB multiplies the value of x by 10.

Page 21: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline21

Program Output

Page 22: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

22

10.9 JavaScript Global Functions

Global function Description escape 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 C, ASCII Character Set) are encoded in a hexadecimal format (see the Number Systems appendix) that can be represented on all platforms.

eval 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.

isFinite 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.

isNaN This function takes a numeric argument and returns true if the value of the argument is not a

number; otherwise, the function 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.

Fig. 10.8 JavaScript global functions.

Page 23: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

23

10.9 JavaScript Global Functions

Global function Description parseFloat This function takes a string argument and attempts to convert the beginning of the string into a

floating-point 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).

parseInt 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 the “Number Systems” appendix for more information on binary, octal and hexadecimal numbers.

unescape This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded.

Fig. 10.8 JavaScript global functions.

Page 24: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

24

11.2 Arrays

c[ 6 ]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

Name of array (Note that all elements of this array have the same name, c)

c[ 0 ]

c[ 1 ]

c[ 2 ]

c[ 3 ]

c[ 11 ]

c[ 10 ]

c[ 9 ]

c[ 8 ]

c[ 7 ]

c[ 5 ]

c[ 4 ]

Position number (index or subscript) of the element within array c

Fig. 11.1 A 12-element array.

Page 25: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

25

11.3 Declaring and Allocating Arrays

Operators Associativity Type

() [] . left to right highest

++ -- ! right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

Fig. 11.2 Precedence and associativity of the operators discussed so far.

Page 26: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline26

InitArray.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 occurs16 function initializeArrays()17 {18 var n1 = new Array( 5 ); // allocate 5-element Array19 var n2 = new Array(); // allocate empty Array20 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 n226 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

Array n1 has five elements.

The for loop initializes the elements in n1 to their subscript numbers (0 to 4).

Array n2 is an empty array.

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.

Page 27: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline27

InitArray.html

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()"></body>55 </html>

The first time function ouputArray is called, variable header gets the value of “Array n1 contains” and variable theArray gets the value of n1.

The second time function ouputArray is called, variable header gets the value of “Array n2 contains” and variable theArray gets the value of n2.

Page 28: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline28

Program Output

Page 29: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline29

InitArray2.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 and17 // 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

Array integers1 is initialized using an initializer list.

Two values are not supplied for integer2, which will be displayed as undefined.

Page 30: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline30

InitArray2.html

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()"></body>49 </html>

Page 31: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline31

Program Output

Page 32: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline32

Program Output

Page 33: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline33

SumArray.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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()"></body>34 </html>

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.

Page 34: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline34

Program Output

Page 35: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline35

RollDie.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 11.6: RollDie.html -->6 <!-- Roll a Six-Sided Die 6000 Times -->7 8 <html xmlns = "http://www.w3.org/1999/xhtml">9 <head>10 <title>Roll a Six-Sided Die 6000 Times</title> 11 12 <script type = "text/javascript"> 13 <!--14 var face, frequency = [ , 0, 0, 0, 0, 0, 0 ]; 15 16 // summarize results17 for ( var roll = 1; roll <= 6000; ++roll ) {18 face = Math.floor( 1 + Math.random() * 6 );19 ++frequency[ face ];20 }21 22 document.writeln( "<table border = \"1\"" + 23 "width = \"100%\">" );24 document.writeln( "<thead><th width = \"100\"" + 25 " align = \"left\">Face<th align = \"left\">" +26 "Frequency</th></thead></tbody>" );27 28 for ( face = 1; face < frequency.length; ++face )29 document.writeln( "<tr><td>" + face + "</td><td>" + 30 frequency[ face ] + "</td></tr>" );31 32 document.writeln( "</tbody></table>" );33 // -->34 </script>35

Referencing Array frequency replaces the switch statement used in Chapter 10’s example.

Page 36: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline36

RollDie.html

Program Output

36 </head>37 <body>38 <p>Click Refresh (or Reload) to run the script again</p>39 </body>40 </html>

Page 37: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline37

PassArray.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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-reference25 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

The first call to function outputArray displays the contents of the Array a before it is modified.

Function modifyArray multiplies each element by 2.

Again, function outputArray is called to show that the contents of Array a have been modified.

The value of a[ 3 ] is output to show its contents before it is modified.

Function modifyElement multiplies the contents of a[ 3 ] by 2.

Page 38: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline38

PassArray.html

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 array47 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()"></body>63 </html>

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.

Page 39: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline39

Program Output

Page 40: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline40

Sort.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 array21 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

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.

Page 41: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline41

Sort.html

Program Output

31 // comparison function for use with sort32 function compareIntegers( value1, value2 )33 {34 return parseInt( value1 ) - parseInt( value2 ); 35 }36 // -->37 </script>38 39 </head><body onload = "start()"></body>40 </html>

Page 42: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline42

LinearSearch.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 Array15 16 // fill Array with even integer values from 0 to 19817 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i;19 20 // function called when "Search" button is pressed21 function buttonPressed()22 {23 var searchKey = searchForm.inputVal.value;24 25 // Array a is passed to linearSearch even though it26 // is a global variable. Normally an array will27 // 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 else34 searchForm.result.value = "Value not found";35 }

Array a 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 Array a and the value of variable searchKey as an integer.

Page 43: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline43

LinearSearch.html

36 37 // Search "theArray" for the specified "key" value38 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 name = "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>

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.

Page 44: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline44

Program Output

Page 45: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline45

BinarySearch.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">4 5 <!-- Fig. 11.10 : BinarySearch.html -->6 <!-- binary search -->7 8 <html xmlns = "http://www.w3.org/1999/xhtml">9 <head>10 <title>Binary Search</title>11 12 <script type = "text/javascript">13 <!--14 var a = new Array( 15 );15 16 for ( var i = 0; i < a.length; ++i )17 a[ i ] = 2 * i;18 19 // function called when "Search" button is pressed20 function buttonPressed()21 {22 var searchKey = searchForm.inputVal.value;23 24 searchForm.result.value = 25 "Portions of array searched\n";26 27 // Array a is passed to binarySearch even though it28 // is a global variable. This is done because 29 // normally an array is passed to a method30 // for searching.31 var element = 32 binarySearch( a, parseInt( searchKey ) );33

Array a is initiated with 15 elements.

Function binarySearch receives two arguments: the Array a and the search key, searchKey.

Page 46: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline46

BinarySearch.html

34 if ( element != -1 )35 searchForm.result.value += 36 "\nFound value in element " + element;37 else38 searchForm.result.value += "\nValue not found";39 }40 41 // Binary search42 function binarySearch( theArray, key ) 43 {44 var low = 0; // low subscript45 var high = theArray.length - 1; // high subscript46 var middle; // middle subscript47 48 while ( low <= high ) {49 middle = ( low + high ) / 2;50 51 // The following line is used to display the 52 // part of theArray currently being manipulated 53 // during each iteration of the binary 54 // search loop.55 buildOutput( theArray, low, middle, high ); 56 57 if ( key == theArray[ middle ] ) // match58 return middle;59 else if ( key < theArray[ middle ] )60 high = middle - 1; // search low end of array61 else62 low = middle + 1; // search high end of array63 }64 65 return -1; // searchKey not found66 }67

If the key matches the middle element of a subarray, the subscript of the current element is returned.

If key is less than the middle element, the high subscript is set to middle – 1.

If key is greater then the middle elements, the high subscript is set to middle +1.

Page 47: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline47

BinarySearch.html

68 // Build one row of output showing the current69 // part of the array being processed.70 function buildOutput( theArray, low, mid, high )71 {72 for ( var i = 0; i < theArray.length; i++ ) {73 if ( i < low || i > high )74 searchForm.result.value += " ";75 // mark middle element in output76 else if ( i == mid )77 searchForm.result.value += a[ i ] + 78 ( theArray[ i ] < 10 ? "* " : "* " );79 else 80 searchForm.result.value += a[ i ] + 81 ( theArray[ i ] < 10 ? " " : " " );82 }83 84 searchForm.result.value += "\n";85 }86 // -->87 </script>88 </head>89 90 <body>91 <form name = "searchForm" action = "">92 <p>Enter integer search key<br />93 <input name = "inputVal" type = "text" />94 <input name = "search" type = "button" value =95 "Search" onclick = "buttonPressed()" /><br /></p>96 <p>Result<br />97 <textarea name = "result" rows = "7" cols = "60">98 </textarea></p>99 </form>100 </body>101 </html>

Function buildOutput creates the markup that displays the results of the search.

Page 48: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline48

Program Output

Page 49: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc. All rights reserved.

49

11.9 Multiple-Subscripted Arrays

a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 0

Row 1

Row 2

Column 0 Column 1 Column 2 Column 3

Row subscript (or index)

Array name

Column subscript (or index)

a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Fig. 11.11 Double-subscripted array with three rows and four columns.

Page 50: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline50

InitArray3.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 row17 [ 4, 5, 6 ] ]; // second row 18 var array2 = [ [ 1, 2 ], // first row19 [ 3 ], // second row20 [ 4, 5, 6 ] ]; // third row21 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

Array array1 provides six initializers in two sublists.

Array array2 provides six initializers in three sublists.

Function outputArray displays each array’s elements in a Web page.

Page 51: 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3

2001 Prentice Hall, Inc.All rights reserved.

Outline51

InitArray3.html

Program Output

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()"></body>44 </html>

Referencing the multidimensional array theArray.