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

Slides:



Advertisements
Similar presentations
JavaScript: Functions
Advertisements

Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Arrays.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
1 JavaScript: Control Structures II. 2 whileCounter.html 1 2
1 Arrays in JavaScript Name of array (Note that all elements of this array have the same name, c ) Position number of the element within array c c[6] c[0]
1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
Page 1 of 26 Javascript/Jscript Ch 7,8,9,10 Vadim Parizher Computer Science Department California State University, Northridge Spring 2003 Slides from.
A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11 – JavaScript/Jscript: Functions Outline 11.1Introduction 11.2Program Modules in JavaScript.
1 JavaScript: Functions and Arrays October 18, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
1 Lecture 3 Part 1 Functions with math and randomness.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
Chapter 6: More JavaScript CIS 275—Web Application Development for Business I.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 6: Introduction to Javascript II r Javascript Objects Array String Date Math.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 18 - WMLScript: Control Structures II Outline 18.1 Introduction 18.2 Essentials of Counter-Controlled.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
1 JavaScript: Control Structures. 2 Control Structures Flowcharting JavaScript’s sequence structure.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
JavaScript, Fourth Edition
Chapter 11: Arrays CIS 275—Web Application Development for Business I.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 16 - WMLScript Functions Outline 16.1 Introduction 16.2 Program Modules in WMLScript 16.3 Programmer-Defined.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
JavaScript: Control Structures I Outline 1 Introduction 2 Algorithms 3 Pseudocode 4 Control Structures 5 if Selection Structure 6 if/else Selection Structure.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Chapter 11 - JavaScript: Arrays
Chapter 17 – JavaScript/Jscript: Arrays
Chapter 10 - JavaScript: Functions
JavaScript: Arrays.
Chapter 11 - JavaScript: Arrays
JavaScript: Functions
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 12 – JavaScript/Jscript: Arrays
Chapter 7 - JavaScript: Introduction to Scripting
10 JavaScript: Arrays.
Chapter 10 - JavaScript: Functions
Presentation transcript:

 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 Recursion Example Using Recursion: Fibonacci Series Recursion vs. Iteration JavaScript Internet and World Wide Web Resources

 2001 Prentice Hall, Inc. All rights reserved Program Modules in JavaScript main worker1worker2worker3 worker4worker5 Fig. 10.1Hierarchical boss-function/worker-function relationship.

 2001 Prentice Hall, Inc. All rights reserved. Outline 3 SquareInt.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " A Programmer-Defined square Function <!-- 14 document.writeln( 15 " Square the numbers from 1 to 10 " ); // square the numbers from 1 to for ( var x = 1; x <= 10; ++x ) 19 document.writeln( "The square of " + x + " is " + 20 square( x ) + " " ); // The following square function's body is executed 23 // only when the function is explicitly called // square function definition 26 function square( y ) 27 { 28 return y * y; 29 } 30 // --> 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 4 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 5 Maximum.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Finding the Maximum of Three Values <!-- 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" ); var value1 = parseFloat( input1 ); 22 var value2 = parseFloat( input2 ); 23 var value3 = parseFloat( input3 ); var maxValue = maximum( value1, value2, value3 ); document.writeln( "First number: " + value " Second number: " + value " Third number: " + value " Maximum is: " + maxValue ); // 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 6 Maximum.html Program Output 36 } 37 // --> Click Refresh (or Reload) to run the script again 43 44

 2001 Prentice Hall, Inc. All rights reserved. Outline 7 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 8 RandomInt.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Shifted and Scaled Random Integers <!-- 14 var value; document.writeln( 17 " " ); 18 document.writeln( 19 " Random Numbers " ); for ( var i = 1; i <= 20; i++ ) { 22 value = Math.floor( 1 + Math.random() * 6 ); 23 document.writeln( " " + value + " " ); // write end and start tags when 26 // i is a multiple of 5 and not if ( i % 5 == 0 && i != 20 ) 28 document.writeln( " " ); 29 } document.writeln( " " ); 32 // --> 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 9 RandomInt.html Program Output Click Refresh (or Reload) to run the script again 38 39

 2001 Prentice Hall, Inc. All rights reserved. Outline 10 RollDie.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Roll a Six-Sided Die 6000 Times <!-- 14 var frequency1 = 0, frequency2 = 0, 15 frequency3 = 0, frequency4 = 0, 16 frequency5 = 0, frequency6 = 0, face; // summarize results 19 for ( var roll = 1; roll <= 6000; ++roll ) { 20 face = Math.floor( 1 + Math.random() * 6 ); 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 11 RollDie.html 36 ++frequency5; 37 break; 38 case 6: 39 ++frequency6; 40 break; 41 } 42 } document.writeln( "<table border = \"1\"" + 45 "width = \"50%\">" ); 46 document.writeln( " Face " + 47 " Frequency " ); 48 document.writeln( " 1 " + 49 frequency1 + " " ); 50 document.writeln( " 2 " + frequency " " ); 52 document.writeln( " 3 " + frequency " " ); 54 document.writeln( " 4 " + frequency " " ); 56 document.writeln( " 5 " + frequency " " ); 58 document.writeln( " 6 " + frequency " " ); 60 // --> Click Refresh (or Reload) to run the script again The results of the dice being rolled 600 times are displayed in a table.

 2001 Prentice Hall, Inc. All rights reserved. Outline 12 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 13 Craps.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 " Program that Simulates the Game of Craps <!-- 14 // variables used to test the state of the game 15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; // 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 // process one roll of the dice 24 function play() 25 { 26 if ( firstRoll ) { // first roll of the dice 27 sumOfDice = rollDice(); switch ( sumOfDice ) { 30 case 7: case 11: // win on first roll 31 gameStatus = WON; 32 // clear point field 33 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 14 Craps.html 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(); if ( sumOfDice == myPoint ) // win by making point 51 gameStatus = WON; 52 else 53 if ( sumOfDice == 7 ) // lose by rolling 7 54 gameStatus = LOST; 55 } 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."; 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 15 Craps.html 71 // roll the dice 72 function rollDice() 73 { 74 var die1, die2, workSum; die1 = Math.floor( 1 + Math.random() * 6 ); 77 die2 = Math.floor( 1 + Math.random() * 6 ); 78 workSum = die1 + die2; document.craps.firstDie.value = die1; 81 document.craps.secondDie.value = die2; 82 document.craps.sum.value = workSum; return workSum; 85 } 86 // --> Craps 94 Die Die Sum Point 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 16 Craps.html Program Output 106 <input type = "button" value = "Roll Dice" 107 onclick = "play()" />

 2001 Prentice Hall, Inc. All rights reserved. Outline 17 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 18 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 19 Scoping.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " A Scoping Example <!-- 14 var x = 1; // global variable function start() 17 { 18 var x = 5; // variable local to function start document.writeln( "local x in start is " + x ); 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 document.writeln( 28 " local x in start is " + x + " " ); 29 } 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 20 Scoping.html document.writeln( " local x in functionA is " + 37 x + " after entering functionA" ); 38 ++x; 39 document.writeln( " local x in functionA is " + 40 x + " before exiting functionA" + " " ); 41 } function functionB() 44 { 45 document.writeln( " global variable x is " + x + 46 " on entering functionB" ); 47 x *= 10; 48 document.writeln( " global variable x is " + 49 x + " on exiting functionB" + " " ); 50 } 51 // --> The value of x is incremented. Function functionB multiplies the value of x by 10.

 2001 Prentice Hall, Inc. All rights reserved. Outline 21 Program Output

 2001 Prentice Hall, Inc. All rights reserved JavaScript Global Functions

 2001 Prentice Hall, Inc. All rights reserved JavaScript Global Functions

 2001 Prentice Hall, Inc. All rights reserved Arrays c[ 6 ] 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.1A 12-element array.

 2001 Prentice Hall, Inc. All rights reserved Declaring and Allocating Arrays

 2001 Prentice Hall, Inc. All rights reserved. Outline 26 InitArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Initializing an Array <!-- 14 // this function is called when the 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 // assign values to each element of Array n1 22 for ( var i = 0; i < n1.length; ++i ) 23 n1[ i ] = i; // create and initialize five-elements in Array n2 26 for ( i = 0; i < 5; ++i ) 27 n2[ i ] = i; 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 27 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( " " + header + " " ); 38 document.writeln( "<table border = \"1\" width =" + 39 "\"100%\">" ); document.writeln( " <th width = \"100\"" + 42 "align = \"left\">Subscript " + 43 " Value " ); for ( var i = 0; i < theArray.length; i++ ) 46 document.writeln( " " + i + " " + 47 theArray[ i ] + " " ); document.writeln( " " ); 50 } 51 // --> 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 28 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 29 InitArray2.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Initializing an Array with a Declaration <!-- 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 ]; 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 30 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( " " + header + " " ); 33 document.writeln( "<table border = \"1\"" + 34 "width = \"100%\">" ); 35 document.writeln( " <th width = \"100\" " + 36 "align = \"left\">Subscript " + 37 " Value " ); for ( var i = 0; i < theArray.length; i++ ) 40 document.writeln( " " + i + " " + 41 theArray[ i ] + " " ); document.writeln( " " ); 44 } 45 // -->

 2001 Prentice Hall, Inc. All rights reserved. Outline 31 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 32 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 33 SumArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Sum the Elements of an Array <!-- 14 function start() 15 { 16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; 17 var total1 = 0, total2 = 0; for ( var i = 0; i < theArray.length; i++ ) 20 total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 ); for ( var element in theArray ) 25 total2 += theArray[ element ]; document.writeln( " Total using for/in: " + 28 total2 ); 29 } 30 // --> 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 34 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 35 RollDie.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Roll a Six-Sided Die 6000 Times <!-- 14 var face, frequency = [, 0, 0, 0, 0, 0, 0 ]; // summarize results 17 for ( var roll = 1; roll <= 6000; ++roll ) { 18 face = Math.floor( 1 + Math.random() * 6 ); 19 ++frequency[ face ]; 20 } document.writeln( "<table border = \"1\"" + 23 "width = \"100%\">" ); 24 document.writeln( " <th width = \"100\"" + 25 " align = \"left\">Face " + 26 "Frequency " ); for ( face = 1; face < frequency.length; ++face ) 29 document.writeln( " " + face + " " + 30 frequency[ face ] + " " ); document.writeln( " " ); 33 // --> Referencing Array frequency replaces the switch statement used in Chapter 10’s example.

 2001 Prentice Hall, Inc. All rights reserved. Outline 36 RollDie.html Program Output Click Refresh (or Reload) to run the script again 39 40

 2001 Prentice Hall, Inc. All rights reserved. Outline 37 PassArray.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Passing Arrays and Individual Array 11 Elements to Functions <!-- 15 function start() 16 { 17 var a = [ 1, 2, 3, 4, 5 ]; document.writeln( " Effects of passing entire " + 20 "array call-by-reference " ); 21 outputArray( 22 "The values of the original array are: ", a ); modifyArray( a ); // array a passed call-by-reference outputArray( 27 "The values of the modified array are: ", a ); document.writeln( " Effects of passing array " + 30 "element call-by-value " + 31 "a[3] before modifyElement: " + a[ 3 ] ); 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 38 PassArray.html 35 document.writeln( 36 " a[3] after modifyElement: " + a[ 3 ] ); 37 } // outputs "header" followed by the contents of "theArray" 40 function outputArray( header, theArray ) 41 { 42 document.writeln( 43 header + theArray.join( " " ) + " " ); 44 } // function that modifies the elements of an array 47 function modifyArray( theArray ) 48 { 49 for ( var j in theArray ) 50 theArray[ j ] *= 2; 51 } // function that attempts to modify the value passed 54 function modifyElement( e ) 55 { 56 e *= 2; 57 document.writeln( " value in modifyElement: " + e ); 58 } 59 // --> 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 39 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 40 Sort.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Sorting an Array with Array Method sort <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( " Sorting an Array " ); 19 outputArray( "Data items in original order: ", a ); 20 a.sort( compareIntegers ); // sort the array 21 outputArray( "Data items in ascending order: ", a ); 22 } // outputs "header" followed by the contents of "theArray" 25 function outputArray( header, theArray ) 26 { 27 document.writeln( " " + header + 28 theArray.join( " " ) + " " ); 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 41 Sort.html Program Output 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // -->

 2001 Prentice Hall, Inc. All rights reserved. Outline 42 LinearSearch.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Linear Search of an Array <!-- 14 var a = new Array( 100 ); // create an Array // fill Array with even integer values from 0 to for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; // 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 ) ); if ( element != -1 ) 31 searchForm.result.value = 32 "Found value in element " + element; 33 else 34 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 43 LinearSearch.html // 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; return -1; 45 } 46 // --> Enter integer search key <input name = "search" type = "button" value = "Search" 56 onclick = "buttonPressed()" /> Result 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 44 Program Output

 2001 Prentice Hall, Inc. All rights reserved. Outline 45 BinarySearch.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 " Binary Search <!-- 14 var a = new Array( 15 ); for ( var i = 0; i < a.length; ++i ) 17 a[ i ] = 2 * i; // function called when "Search" button is pressed 20 function buttonPressed() 21 { 22 var searchKey = searchForm.inputVal.value; searchForm.result.value = 25 "Portions of array searched\n"; // Array a is passed to binarySearch even though it 28 // is a global variable. This is done because 29 // normally an array is passed to a method 30 // 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 46 BinarySearch.html 34 if ( element != -1 ) 35 searchForm.result.value += 36 "\nFound value in element " + element; 37 else 38 searchForm.result.value += "\nValue not found"; 39 } // Binary search 42 function binarySearch( theArray, key ) 43 { 44 var low = 0; // low subscript 45 var high = theArray.length - 1; // high subscript 46 var middle; // middle subscript while ( low <= high ) { 49 middle = ( low + high ) / 2; // 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 ); if ( key == theArray[ middle ] ) // match 58 return middle; 59 else if ( key < theArray[ middle ] ) 60 high = middle - 1; // search low end of array 61 else 62 low = middle + 1; // search high end of array 63 } return -1; // searchKey not found 66 } 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 47 BinarySearch.html 68 // Build one row of output showing the current 69 // 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 high ) 74 searchForm.result.value += " "; 75 // mark middle element in output 76 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 } searchForm.result.value += "\n"; 85 } 86 // --> Enter integer search key <input name = "search" type = "button" value = 95 "Search" onclick = "buttonPressed()" /> 96 Result Function buildOutput creates the markup that displays the results of the search.

 2001 Prentice Hall, Inc. All rights reserved. Outline 48 Program Output

 2001 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Fig Double-subscripted array with three rows and four columns.

 2001 Prentice Hall, Inc. All rights reserved. Outline 50 InitArray3.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Initializing Multidimensional Arrays <!-- 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 outputArray( "Values in array1 by row", array1 ); 23 outputArray( "Values in array2 by row", array2 ); 24 } function outputArray( header, theArray ) 27 { 28 document.writeln( " " + header + " " ); 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.

 2001 Prentice Hall, Inc. All rights reserved. Outline 51 InitArray3.html Program Output 30 for ( var i in theArray ) { for ( var j in theArray[ i ] ) 33 document.write( theArray[ i ][ j ] + " " ); document.writeln( " " ); 36 } document.writeln( " " ); 39 } 40 // --> Referencing the multidimensional array theArray.