Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 - JavaScript: Arrays

Similar presentations


Presentation on theme: "Chapter 11 - JavaScript: Arrays"— Presentation transcript:

1 Chapter 11 - JavaScript: Arrays
Outline Introduction Arrays Declaring and Allocating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Functions Sorting Arrays Searching Arrays: Linear Search and Binary Search Multiple-Subscripted Arrays JavaScript Internet and World Wide Web Resources

2 11.2 Arrays c c Fig. 11.1 A 12-element array. c[ 0 ] -45 c[ 1 ] 6
Name of array (Note that all elements of c[ 1 ] 6 this array have the same name, c ) c[ 2 ] c[ 3 ] 72 c[ 4 ] 1543 c[ 5 ] -89 c[ 6 ] 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 Fig A 12-element array.

3 11.3 Declaring and Allocating Arrays

4 Array n1 has five elements.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.3: InitArray.html --> 6 <!-- Initializing an Array > 7 8 <html xmlns = " <head> <title>Initializing an Array</title> 11 <script type = "text/javascript"> <!-- // this function is called when the <body> element's // onload event occurs function initializeArrays() { var n1 = new Array( 5 ); // allocate 5-element Array var n2 = new Array(); // allocate empty Array 20 // assign values to each element of Array n1 for ( var i = 0; i < n1.length; ++i ) n1[ i ] = i; 24 // create and initialize five-elements in Array n2 for ( i = 0; i < 5; ++i ) n2[ i ] = i; 28 outputArray( "Array n1 contains", n1 ); outputArray( "Array n2 contains", n2 ); } 32 InitArray.html Array n1 has five elements. Array n2 is an empty array. The for loop initializes the elements in n1 to their subscript numbers (0 to 4). 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.

5 33 // output "header" followed by a two-column table
// containing subscripts and elements of "theArray" function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\" width =" + "\"100%\">" ); 40 document.writeln( "<thead><th width = \"100\"" + "align = \"left\">Subscript</th>" + "<th align = \"left\">Value</th></thead><tbody>" ); 44 for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); 48 document.writeln( "</tbody></table>" ); } // --> </script> 53 </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. InitArray.html

6 Program Output

7 Array integers1 is initialized using an initializer list.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.4: InitArray2.html > 6 <!-- Initializing an Array with a Declaration --> 7 8 <html xmlns = " <head> <title>Initializing an Array with a Declaration</title> 11 <script type = "text/javascript"> <!-- function start() { // Initializer list specifies number of elements and // value for each element. var colors = new Array( "cyan", "magenta", "yellow", "black" ); var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ]; 22 outputArray( "Array colors contains", colors ); outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); } 27 InitArray2.html Array integers1 is initialized using an initializer list. Two values are not supplied for integer2, which will be displayed as undefined.

8 InitArray2.html 28 // output "header" followed by a two-column table
// containing subscripts and elements of "theArray" function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2>" ); document.writeln( "<table border = \"1\"" + "width = \"100%\">" ); document.writeln( "<thead><th width = \"100\" " + "align = \"left\">Subscript</th>" + "<th align = \"left\">Value</th></thead><tbody>" ); 38 for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); 42 document.writeln( "</tbody></table>" ); } // --> </script> 47 </head><body onload = "start()"></body> 49 </html> InitArray2.html

9 Program Output

10 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.5: SumArray.html > 6 <!-- Summing Elements of an Array --> 7 8 <html xmlns = " <head> <title>Sum the Elements of an Array</title> 11 <script type = "text/javascript"> <!-- function start() { var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0, total2 = 0; 18 for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; 21 document.writeln( "Total using subscripts: " + total1 ); 23 for ( var element in theArray ) total2 += theArray[ element ]; 26 document.writeln( "<br />Total using for/in: " + total2 ); } // --> </script> 32 </head><body onload = "start()"></body> 34 </html> SumArray.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.

11 Program Output

12 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.6: RollDie.html > 6 <!-- Roll a Six-Sided Die 6000 Times --> 7 8 <html xmlns = " <head> <title>Roll a Six-Sided Die 6000 Times</title> 11 <script type = "text/javascript"> <!-- var face, frequency = [ , 0, 0, 0, 0, 0, 0 ]; 15 // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); frequency[ face ]; } 21 document.writeln( "<table border = \"1\"" + "width = \"100%\">" ); document.writeln( "<thead><th width = \"100\"" + " align = \"left\">Face<th align = \"left\">" + "Frequency</th></thead></tbody>" ); 27 for ( face = 1; face < frequency.length; ++face ) document.writeln( "<tr><td>" + face + "</td><td>" + frequency[ face ] + "</td></tr>" ); 31 document.writeln( "</tbody></table>" ); // --> </script> 35 RollDie.html Referencing Array frequency replaces the switch statement used in Chapter 10’s example.

13 RollDie.html Program Output
</head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> 40 </html> RollDie.html Program Output

14 Function modifyArray multiplies each element by 2.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.7: PassArray.html --> 6 <!-- Passing Arrays > 7 8 <html xmlns = " <head> <title>Passing Arrays and Individual Array Elements to Functions</title> 12 <script type = "text/javascript"> <!-- function start() { var a = [ 1, 2, 3, 4, 5 ]; 18 document.writeln( "<h2>Effects of passing entire " + "array call-by-reference</h2>" ); outputArray( "The values of the original array are: ", a ); 23 modifyArray( a ); // array a passed call-by-reference 25 outputArray( "The values of the modified array are: ", a ); 28 document.writeln( "<h2>Effects of passing array " + "element call-by-value</h2>" + "a[3] before modifyElement: " + a[ 3 ] ); 32 modifyElement( a[ 3 ] ); 34 PassArray.html The first call to function outputArray displays the contents of the Array a before it is modified. Function modifyArray multiplies each element by 2. The value of a[ 3 ] is output to show its contents before it is modified. Again, function outputArray is called to show that the contents of Array a have been modified. Function modifyElement multiplies the contents of a[ 3 ] by 2.

15 Multiply each element in theArray by 2.
document.writeln( "<br />a[3] after modifyElement: " + a[ 3 ] ); } 38 // outputs "header" followed by the contents of "theArray" function outputArray( header, theArray ) { document.writeln( header + theArray.join( " " ) + "<br />" ); } 45 // function that modifies the elements of an array function modifyArray( theArray ) { for ( var j in theArray ) theArray[ j ] *= 2; } 52 // function that attempts to modify the value passed function modifyElement( e ) { e *= 2; document.writeln( "<br />value in modifyElement: " + e ); } // --> </script> 61 </head><body onload = "start()"></body> 63 </html> PassArray.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.

16 Program Output

17 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.8: sort.html --> 6 <!-- Sorting an Array > 7 8 <html xmlns = " <head> <title>Sorting an Array with Array Method sort</title> 11 <script type = "text/javascript"> <!-- function start() { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 17 document.writeln( "<h1>Sorting an Array</h1>" ); outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); // sort the array outputArray( "Data items in ascending order: ", a ); } 23 // outputs "header" followed by the contents of "theArray" function outputArray( header, theArray ) { document.writeln( "<p>" + header + theArray.join( " " ) + "</p>" ); } 30 Sort.html 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.

18 Sort.html Program Output
// comparison function for use with sort function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); } // --> </script> 38 </head><body onload = "start()"></body> 40 </html> Sort.html Program Output

19 Array a is initiated with 100 elements.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 11.9: LinearSearch.html --> 6 <!-- Linear Search of an Array --> 7 8 <html xmlns = " <head> <title>Linear Search of an Array</title> 11 <script type = "text/javascript"> <!-- var a = new Array( 100 ); // create an Array 15 // fill Array with even integer values from 0 to 198 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; 19 // function called when "Search" button is pressed function buttonPressed() { var searchKey = searchForm.inputVal.value; 24 // Array a is passed to linearSearch even though it // is a global variable. Normally an array will // be passed to a method for searching. var element = linearSearch( a, parseInt( searchKey ) ); 29 if ( element != -1 ) searchForm.result.value = "Found value in element " + element; else searchForm.result.value = "Value not found"; } LinearSearch.html 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.

20 Function linearSearch compares each each element with a search key.
36 // Search "theArray" for the specified "key" value function linearSearch( theArray, key ) { for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; 43 return -1; } // --> </script> 48 </head> 50 <body> <form name = "searchForm" action = ""> <p>Enter integer search key<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p> 57 <p>Result<br /> <input name = "result" type = "text" size = "30" /></p> </form> </body> 62 </html> Variable theArray gets the value of Array a and variable key gets the value of variable searchKey. Function linearSearch compares each each element with a search key. LinearSearch.html

21 Program Output

22 Array a is initiated with 15 elements.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 4 5 <!-- Fig : BinarySearch.html --> 6 <!-- binary search > 7 8 <html xmlns = " <head> <title>Binary Search</title> 11 <script type = "text/javascript"> <!-- var a = new Array( 15 ); 15 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; 18 // function called when "Search" button is pressed function buttonPressed() { var searchKey = searchForm.inputVal.value; 23 searchForm.result.value = "Portions of array searched\n"; 26 // Array a is passed to binarySearch even though it // is a global variable. This is done because // normally an array is passed to a method // for searching. var element = binarySearch( a, parseInt( searchKey ) ); 33 BinarySearch.html Array a is initiated with 15 elements. Function binarySearch receives two arguments: the Array a and the search key, searchKey.

23 if ( element != -1 ) searchForm.result.value += "\nFound value in element " + element; else searchForm.result.value += "\nValue not found"; } 40 // Binary search function binarySearch( theArray, key ) { var low = 0; // low subscript var high = theArray.length - 1; // high subscript var middle; // middle subscript 47 while ( low <= high ) { middle = ( low + high ) / 2; 50 // The following line is used to display the // part of theArray currently being manipulated // during each iteration of the binary // search loop. buildOutput( theArray, low, middle, high ); 56 if ( key == theArray[ middle ] ) // match return middle; else if ( key < theArray[ middle ] ) high = middle - 1; // search low end of array else low = middle + 1; // search high end of array } 64 return -1; // searchKey not found } 67 BinarySearch.html 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.

24 68 // Build one row of output showing the current
// part of the array being processed. function buildOutput( theArray, low, mid, high ) { for ( var i = 0; i < theArray.length; i++ ) { if ( i < low || i > high ) searchForm.result.value += " "; // mark middle element in output else if ( i == mid ) searchForm.result.value += a[ i ] + ( theArray[ i ] < 10 ? "* " : "* " ); else searchForm.result.value += a[ i ] + ( theArray[ i ] < 10 ? " " : " " ); } 83 searchForm.result.value += "\n"; } // --> </script> </head> 89 <body> <form name = "searchForm" action = ""> <p>Enter integer search key<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p> <p>Result<br /> <textarea name = "result" rows = "7" cols = "60"> </textarea></p> </form> </body> 101 </html> Function buildOutput creates the markup that displays the results of the search. BinarySearch.html

25 Program Output

26 11.9 Multiple-Subscripted Arrays
Fig Double-subscripted array with three rows and four columns.

27 Array array1 provides six initializers in two sublists.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : InitArray3.html > 6 <!-- Initializing Multidimensional Arrays --> 7 8 <html xmlns = " <head> <title>Initializing Multidimensional Arrays</title> 11 <script type = "text/javascript"> <!-- function start() { var array1 = [ [ 1, 2, 3 ], // first row [ 4, 5, 6 ] ]; // second row var array2 = [ [ 1, 2 ], // first row [ 3 ], // second row [ 4, 5, 6 ] ]; // third row 21 outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); } 25 function outputArray( header, theArray ) { document.writeln( "<h2>" + header + "</h2><tt>" ); 29 InitArray3.html 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.

28 InitArray3.html Program Output
for ( var i in theArray ) { 31 for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); 34 document.writeln( "<br />" ); } 37 document.writeln( "</tt>" ); } // --> </script> 42 </head><body onload = "start()"></body> 44 </html> InitArray3.html Program Output Referencing the multidimensional array theArray.


Download ppt "Chapter 11 - JavaScript: Arrays"

Similar presentations


Ads by Google