Javascript: Functions and Arrays: October 18, 2005
Javascript: Functions and Arrays: October 18, 2005
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 Another Example: Random Image Generator
10.8 Scope Rules
10.9 JavaScript Global Functions
10.10 Recursion
10.11 Recursion vs. Iteration
10.12 Web Resources
2
Objectives
• In this tutorial, you will learn:
– To understand how to construct programs
modularly from small pieces called functions.
– To be able to create new functions.
– To understand the mechanisms used to pass
information between functions.
– To introduce simulation techniques that use
random-number generation.
– To understand how the visibility of identifiers
is limited to specific regions of programs.
3
10.2 Program Modules in
JavaScript
• Modules in JavaScript
– Functions
– Methods
• Belong to an object
– JavaScript includes many useful pre-
defined methods
• Combine with programmer-defined methods to
make a program
4
10.2 Program Modules in
JavaScript
• Function calls
– Name
– Left parenthesis
– Arguments separated by commas
• Constants, variables or expressions
– Right parenthesis
– Examples:
6
10.4 Function Definitions
• Format of a function definition
8
10.4 Function Definitions
• Writing a function to square two
numbers
– for loop from 1 to 10
– Pass each number as argument to square
– return value of argument multiplied by
itself
– Display result
9
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(
Calling function square and passing it the value of x.
15 "<h1>Square the numbers from 1 to 10</h1>" );
16
17 // square the numbers from 1 to 10
18 for ( var x = 1; x <= 10; ++x )
19 document.writeln( "The square of " + x + " is " +
20 square( x ) + "<br />" );
21
Variable y gets the value of variable x.
12
44 document.writeln( "<table border = \"1\"" +
45 "width = \"50%\">" );
46 document.writeln( "<thead><th>Face</th>" +
The results of rolling the die
47 "<th>Frequency<th></thead>" );
600 times are displayed in a
48 document.writeln( "<tbody><tr><td>1</td><td>" +
table.
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>" );
RollDie.html
54 document.writeln( "<tr><td>4</td><td>" + frequency4 +
55 "</td></tr>" );
56 document.writeln( "<tr><td>5</td><td>" + frequency5 +
57
58
59
"</td></tr>" );
(3 of 3)
document.writeln( "<tr><td>6</td><td>" + frequency6 +
"</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>
13
10.7 Another Example:
Random Image Generator
• Randomly selecting an image
– Images have integer names (i.e., 1.gif,
2.gif, …, 7.gif)
– Generate random number in proper range
– Update src property
14
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig.Inserting a random number
10.7: RandomPicture.html into-->
the image’s src
6 <!-- property
Randomly with document.write
displays one of 7 images -->and Math.random
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Random Image Generator</title>
11
12
13
RandomPicture.html
<script type = "text/javascript">
<!--
14
15
(1 of 1)
document.write ( "<img src = \"" +
Math.floor( 1 + Math.random() * 7 ) +
16 ".gif\" width = \"105\" height = \"100\" />" );
17 // -->
18 </script>
19
20 </head>
21
22 <body>
23 <p>Click Refresh (or Reload) to run the script again</p>
24 </body>
25 </html>
15
10.8 Scope Rules
• Scope
– Portion of program where identifier can be
referenced
– Inside function is local or function scope
• Identifiers exist only between opening and
closing braces
• Local variables hide global variables
16
10.8 Scope Rules
• Scope demonstration
– Global variable x initialized to 1
– start has local variable x initialized to 5
– functionA has local variable x initialized to
25
– functionB has no local variable x
– Observe output of each function
17
To begin the program, variable x is initialized to 1.
26
27 document.writeln(
28 "<p>local x in start is " + x + "</p>" );
29 }
30
31 function functionA()
32 { Function start changes the value of x to 5.
33 var x = 25; // initialized each time
34 // functionA is called
35 Function functionA changes the value of x to 25.
36 document.writeln( "<p>local x in functionA is " +
37 x + " after entering functionA" ); The value of x is incremented.
38 ++x;
39 document.writeln( "<br />local x in functionA is " +
40 x + " before exiting functionA" + "</p>" );
41 }
42
19
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 D, ASCII
Character Set) are encoded in a hexadecimal format
(see Appendix E, Number Systems) 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, 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.
Fig. 10.9 JavaScript global functions. 20
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 Appendex E, Number
Systems, 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. 21
Fig. 10.9 JavaScript global functions.
10.10 Recursion
• Recursive functions
– Call themselves
• Recursion step or recursive call
• Part of return statement
– Must have base case
• Simplest case of problem
• Returns value rather than calling itself
– Each recursive call simplifies input
• When simplified to base case, functions return
22
JavaScript: Functions and Arrays
23
Chapter 11 - JavaScript: Arrays
Outline
11.1 Introduction
11.2 Arrays
11.3 Declaring and Allocating Arrays
11.4 Examples Using Arrays
11.5 Random Image Generator Using Arrays
11.6 References and Reference Parameters
11.7 Passing Arrays to Functions
11.8 Sorting Arrays
11.9 Searching Arrays: Linear Search and Binary Search
11.10 Multidimensional Arrays
11.11 Building an Online Quiz
11.12 Web Resources
24
Objectives
• In this tutorial, you will learn:
– To introduce the array data structure.
– To understand the use of arrays to store,
sort and search lists and tables of values.
– To understand how to declare an array,
initialize an array and refer to individual
elements of an array.
– To be able to pass arrays to functions.
– To be able to search and sort an array.
– To be able to declare and manipulate multi-
dimensional arrays. 25
11.1 Introduction
• Arrays
– Data structures of related items
• Also called Collections
– Dynamic
26
11.2 Arrays
• Arrays in JavaScript
– Each element referenced by a number
• Start at “zeroth element”
• Subscript or index
– Accessing a specific element
• Name of array
• Brackets
• Number of element
– Arrays know their length
• length property
27
11.2 Arrays
c[ 0 ] -45
Name of array
c[ 1 ] 6
c[ 2 ] 0
c[ 3 ] 72
c[ 4 ] 1543
c[ 5 ] -89
c[ 6 ] 0
c[ 7 ] 62
c[ 8 ] -3
c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within array c
c[ 11 ] 78
28
11.3 Declaring and
Allocating Arrays
• Arrays in memory
– Objects
– Operator new
• Allocates memory for objects
• Dynamic memory allocation operator
var c;
c = new Array( 12 );
or
29
11.4 Examples Using
Arrays
• Arrays grow dynamically
– Allocate more space as items are added
• Must initialize array elements
– Default value is undefined
– for loops convenient
– Referring to uninitialized elements or
elements outside array bounds is an error
30
31
11.4 Examples Using
Arrays
• Possible to declare and initialize in one step
– Specify list of values
• Initializer list
var n = [ 10, 20, 30, 40, 50 ];
var n = new Array( 10, 20, 30, 40,
50 );
– Also possible to only initialize some values
• Leave uninitialized elements blank
• Uninitialized elements default to “undefined”
var n = [ 10, 20, , 40, 50 ];
32
27
28 // output "header" followed by a two-column table
29 // containing subscripts and elements of "theArray"
30 function outputArray( header, theArray )
31 {
32 document.writeln( "<h2>" + header + "</h2>" );
33 document.writeln( "<table border = \"1\"" +
34 "width = \"100%\">" );
35 document.writeln( "<thead><th width = \"100\" " +
36 "align = \"left\">Subscript</th>" +
37 "<th align = \"left\">Value</th></thead><tbody>" );
38
39 for ( var i = 0; i < theArray.length; i++ )
40 document.writeln( "<tr><td>" + i + "</td><td>" +
41 theArray[ i ] + "</td></tr>" );
42
43 document.writeln( "</tbody></table>" );
44 }
45 // -->
46 </script>
47
48 </head><body onload = "start()"></body> 33
49 </html>
11.4 Examples Using
Arrays
• for…in statement
– Perform an action for each element in an
array
– Iterates over array elements
• Assigns each element to specified variable one at
a time
– Ignores non-existent elements
34
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 The for loop sums the values contained in the 10-
element integer array called theArray.
SumArray.html
12 <script type = "text/javascript">
13 <!--
14 function start()
15 {
16
17
18
var total1 = 0, total2 = 0; (1 of 2)
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
36
5 <!-- Fig. 11.6: RollDie.html -->
6 <!-- Roll a Six-Sided Die 6000 Times -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml"> Referencing Array frequency replaces the switch
9
10
<head>
<title>Roll a Six-Sided Die 6000 Times</title>
statement used in Chapter 10’s example.
11
12 <script type = "text/javascript">
13 <!--
14 var face, frequency = [ , 0, 0, 0, 0, 0, 0 ];
15
16 // summarize results
17 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
36 </head>
37 <body>
38 <p>Click Refresh (or Reload) to run the script again</p>
39 </body> 37
40 </html>
11.5 Random Image
Generator Using Arrays
• Cleaner approach than previous version
– Specify any file name rather than integers 1-7
– Result of Math.random call is index into array
of image file names
38
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 11.7: RandomPicture2.html -->
6 <!-- Randomly displays one of 7 images -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
RandomPicture2
9 <head>
10 <title>Random Image Generator</title>
11
.html
12 <script type = "text/javascript">
13 <!--
14 var pictures =
15
16
17
(1 of 2)
[ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];
PassArray.html
(1 of 3)
42
26 outputArray(
27 "The values of the modified array are: ", a );
28
29
Again, function outputArray is called to show
document.writeln( "<h2>Effects of passing array " +
30 "element
that the contents of Array a have been modified.
call-by-value</h2>" +
31 "a[3] before modifyElement: " + a[ 3 ] );
32
33 modifyElement( a[ 3 ] );
Function modifyElement multiplies the
34
contents of a[ 3 ] by 2.
35 document.writeln(
36
37
38
} PassArray.html
"<br />a[3] after modifyElement: " + a[ 3 ] ); The value of a[ 3 ] is output to show its
contents before it is modified.
39
40
(2 of 3)
// outputs "header" followed by the contents of "theArray"
function outputArray( header, theArray )
41 {
42 document.writeln(
43 header + theArray.join( " " ) + "<br />" );
44 }
45
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.
43
46 // function that modifies the elements of an array
47 function modifyArray( theArray )
48 {
49 for ( var j in theArray )
50 theArray[ j ] *= 2;
51 }
52
53 // function that attempts to modify the value passed
54 function modifyElement( e ) Multiply each element in theArray by 2.
55 {
PassArray.html
56 e *= 2;
57 document.writeln( "<br />value in modifyElement: " + e );
58 }
59
60
61
// -->
</script> (3 of 3)
62 </head><body onload = "start()"></body>
63 </html>
44
11.8 Sorting Arrays
• Sorting
– Important computing task
• Array.sort
– Defaults to string comparison
– Optional comparator function
• Return negative if first argument less than second
• Return zero if arguments equal
• Return positive if first argument greater than
second
45
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.
23
Sort.html
24
25
26
(1 of 2)
// outputs "header" followed by the contents of "theArray"
function outputArray( header, theArray )
{
27 document.writeln( "<p>" + header +
28 theArray.join( " " ) + "</p>" );
29 }
30
31 // comparison function for use with sort
32 function compareIntegers( value1, value2 )
33 {
34 return parseInt( value1 ) - parseInt( value2 );
35
Function compareIntegers calculates the
}
36 // -->
difference between the integer values of its
37 </script> arguments.
38
39 </head><body onload = "start()"></body>
46
40 </html>
11.9 Searching Arrays: Linear
Search and Binary Search
• Searching
– Look for matching key value
• Linear search
– Iterate through each element until match found
– Inefficient
• Worst case scenario, must test entire array
• Binary search
– Requires sorted data
– Cuts search range in half each iteration
– Efficient
• Only look at small fraction of elements
47
Array a is initiated with 100 elements.
</head>
LinearSearch.html
50
51 <body>
(3 of 3)
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>
49
11.9 Searching Arrays: Binary
Fig. 11.11
Search
Binary search of an array.
50
11.10 Multidimensional
Arrays
• Two-dimensional arrays analogous to
tables
– Rows and columns
• Specify row first, then column
– Two subscripts
51
11.10 Multidimensional
Arrays
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Array name
Fig. 11.12 Two-dimensional array with three rows and four columns.
52
11.10 Multidimensional
Arrays
• Declaring and initializing multidimensional
arrays
– Group by row in square brackets
– Treated as arrays of arrays
– Creating array b with one row of two elements
and a second row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
53
11.10 Multidimensional
Arrays
• Also possible to use new operator
– Create array b with two rows, first with five
columns and second with three:
var b;
b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );
54
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.13: InitArray3.html -->
6 <!-- Initializing Multidimensional Arrays -->
7
8 Array array1
<html xmlns = "http://www.w3.org/1999/xhtml"> provides six initializers in
9 <head> two rows.
10 <title>Initializing Multidimensional Arrays</title>
11
12
13
InitArray3.html
<script type = "text/javascript">
Array array2 provides six initializers in
three rows.
(1 of 2)
<!--
14 function start()
15 {
16 var array1 = [ [ 1, 2, 3 ], // first row
17 [ 4, 5, 6 ] ]; // second row
18 var array2 = [ [ 1, 2 ], Function
// first row outputArray displays each array’s
19 [ 3 ], // second elements
row in a Web page.
20 [ 4, 5, 6 ] ]; // third row
21
22 outputArray( "Values in array1 by row", array1 );
23 outputArray( "Values in array2 by row", array2 );
24 }
55
25
26 function outputArray( header, theArray )
27 {
28 document.writeln( "<h2>" + header + "</h2><tt>" );
29
30 for ( var i in theArray ) {
31
32 for ( var j in theArray[ i ] )
33 document.write( theArray[ i ][ j ] + " " );
34
InitArray3.html
35 document.writeln( "<br />" );
36 }
37
Referencing the multidimensional
array theArray.
38
39
40
}
// -->
(2 of 2)
document.writeln( "</tt>" );
41 </script>
42
43 </head><body onload = "start()"></body>
44 </html>
56
11.11 Building an Online
Quiz
• Radio buttons
– Represented as an array
• Name of radio buttons is name of array
• One element per button
– checked property is true when selected
• XHTML Forms
– Contain controls, including radio buttons
– action property specifies what happens when
submitted
• Can call JavaScript code
57
Quiz.html
(2 of 2)
Call the checkAnswers function
when the form is submitted.
58