SlideShare a Scribd company logo
1 of 61
IPA
1st
Semester, 2007-2008
Internet 1
Ch. 12
JavaScript: Arrays
attasr@ipa.edu.sa
09/30/15 © Reem Al-Attas 2
Introduction
Arrays
 Data structures of related items
 Also called Collections
 Dynamic
09/30/15 © Reem Al-Attas 3
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
09/30/15 © Reem Al-Attas 4
Arrays
c[ 6 ]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array 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.
09/30/15 © Reem Al-Attas 5
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.
09/30/15 © Reem Al-Attas 6
Declaring and Allocating Arrays
Arrays in memory
 Objects
 Operator new
 Allocates memory for objects
 Dynamic memory allocation operator
var c;
c = new Array( 12 );
09/30/15 © Reem Al-Attas 7
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
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 occurs
16 function initializeArrays()
17 {
18 var n1 = new Array( 5 ); // allocate 5-element Array
19 var n2 = new Array(); // allocate empty Array
20
21 // assign values to each element of Array n1
22 for ( var i = 0; i < n1.length; ++i )
23 n1[ i ] = i;
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.
24
25 // create and initialize five-elements in Array n2
26 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
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>" );
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.
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.
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>
09/30/15 © Reem Al-Attas 11
Examples Using Arrays
09/30/15 © Reem Al-Attas 12
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 ];
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 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 ];
22
23 outputArray( "Array colors contains", colors );
24 outputArray( "Array integers1 contains", integers1 );
25 outputArray( "Array integers2 contains", integers2 );
26 }
Array integers1 is initialized using an initializer list.
Two values are not supplied for integers2,
which will be displayed as undefined.
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>
49 </html>
09/30/15 © Reem Al-Attas 15
Examples Using Arrays
09/30/15 © Reem Al-Attas 16
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
SumArray.html
(1 of 2)
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
The for loop sums the values contained in the 10-
element integer array called theArray.
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>
Variable element is assigned a subscript
in the range of 0 up to, but not including,
theArray.length.
09/30/15 © Reem Al-Attas 19
Examples Using Arrays
09/30/15 © Reem Al-Attas 20
Examples Using Arrays
Arrays can provide shorter and cleaner
substitute for switch statements
 Each element represents one case
RollDie.html
(1 of 2)
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 results
17 for ( var roll = 1; roll <= 6000; ++roll ) {
18 face = Math.floor( 1 + Math.random() * 6 );
19 ++frequency[ face ];
20 }
21
Referencing Array frequency replaces the switch
statement used in Chapter 10’s example.
RollDie.html
(2 of 2)
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>
40 </html>
09/30/15 © Reem Al-Attas 23
Examples Using Arrays
09/30/15 © Reem Al-Attas 24
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
RandomPicture2
.html
(1 of 2)
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">
9 <head>
10 <title>Random Image Generator</title>
11
12 <script type = "text/javascript">
13 <!--
14 var pictures =
15 [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];
RandomPicture2
.html
(2 of 2)
16
17 document.write ( "<img src = "" +
18 pictures[ Math.floor( Math.random() * 7 ) ] +
19 ".gif" width = "105" height = "100" />" );
20 // -->
21 </script>
22
23 </head>
24
25 <body>
26 <p>Click Refresh (or Reload) to run the script again</p>
27 </body>
28 </html>
09/30/15 © Reem Al-Attas 27
Random Image Generator Using
Arrays
09/30/15 © Reem Al-Attas 28
References and Reference
Parameters
Two ways to pass parameters
 Pass-by-value
 Pass copy of original value
 Default for numbers and booleans
 Original variable is unchanged
 Pass-by-reference
 How objects are passed, like arrays
 Pass location in memory of value
 Allows direct access to original value
 Improves performance
09/30/15 © Reem Al-Attas 29
Passing Arrays to Functions
Name of array is argument
 Not necessary to also pass size of array
 Arrays know their size
 Passed by reference
 Individual elements are passed by value if numbers
or booleans
 Array.join
 Creates string containing all array elements
 Specify separator
PassArray.html
(1 of 3)
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: 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-reference
25
The first call to function outputArray displays the
contents of the Array a before it is modified.
Function modifyArray multiplies each element by 2.
PassArray.html
(2 of 3)
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
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
Again, function outputArray is called to show
that the contents of Array a have been modified.
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.
Function modifyElement multiplies the
contents of a[ 3 ] by 2.
The value of a[ 3 ] is output to show its
contents before it is modified.
PassArray.html
(3 of 3)
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 )
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>
Multiply each element in theArray by 2.
09/30/15 © Reem Al-Attas 33
Passing Arrays to Functions
09/30/15 © Reem Al-Attas 34
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
Sort.html
(1 of 2)
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: 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 array
21 outputArray( "Data items in ascending order: ", a );
22 }
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.
Sort.html
(2 of 2)
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
31 // comparison function for use with sort
32 function compareIntegers( value1, value2 )
33 {
34 return parseInt( value1 ) - parseInt( value2 );
35 }
36 // -->
37 </script>
38
39 </head><body onload = "start()"></body>
40 </html>
Function compareIntegers calculates the difference
between the integer values of its arguments.
09/30/15 © Reem Al-Attas 37
Sorting Arrays
09/30/15 © Reem Al-Attas 38
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
LinearSearch.html
(1 of 3)
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.10: 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 Array
15
16 // fill Array with even integer values from 0 to 198
17 for ( var i = 0; i < a.length; ++i )
18 a[ i ] = 2 * i;
19
Array a is initiated with 100 elements.
Array a is populated with the even integers 0 to 198.
LinearSearch.html
(2 of 3)
20 // function called when "Search" button is pressed
21 function buttonPressed()
22 {
23 var searchKey = searchForm.inputVal.value;
24
25 // 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 ) );
29
30 if ( element != -1 )
31 searchForm.result.value =
32 "Found value in element " + element;
33 else
34 searchForm.result.value = "Value not found";
35 }
36
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.
LinearSearch.html
(3 of 3)
37 // 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;
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>
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.
09/30/15 © Reem Al-Attas 42
Searching Arrays: Linear Search
and Binary Search
BinarySearch.html
(1 of 5)
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.11 : 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
Array a is initialized with 15 elements.
BinarySearch.html
(2 of 5)
19 // function called when "Search" button is pressed
20 function buttonPressed()
21 {
22 var searchKey = searchForm.inputVal.value;
23
24 searchForm.result.value =
25 "Portions of array searchedn";
26
27 // 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
34 if ( element != -1 )
35 searchForm.result.value +=
36 "nFound value in element " + element;
37 else
38 searchForm.result.value += "nValue not found";
39 }
40
Function binarySearch receives two arguments:
the Array a and the search key, searchKey.
BinarySearch.html
(3 of 5)
41 // 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
47
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 ] ) // 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 }
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.
BinarySearch.html
(4 of 5)
64
65 return -1; // searchKey not found
66 }
67
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 < low || i > high )
74 searchForm.result.value += " ";
75 // mark middle element in output
76 else if ( i == mid )
77 searchForm.result.value += theArray[ i ] +
78 ( theArray[ i ] < 10 ? "* " : "* " );
79 else
80 searchForm.result.value += theArray[ i ] +
81 ( theArray[ i ] < 10 ? " " : " " );
82 }
83
84 searchForm.result.value += "n";
85 }
86 // -->
87 </script>
88 </head>
89
Function buildOutput creates the markup that
displays the results of the search.
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>
09/30/15 © Reem Al-Attas 48
Searching Arrays: Linear Search
and Binary Search
09/30/15 © Reem Al-Attas 49
Multidimensional Arrays
Two-dimensional arrays analogous to
tables
 Rows and columns
 Specify row first, then column
 Two subscripts
09/30/15 © Reem Al-Attas 50
Multidimensional 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.12 Two-dimensional array with three rows and four columns.
09/30/15 © Reem Al-Attas 51
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 ] ];
09/30/15 © Reem Al-Attas 52
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 );
InitArray3.html
(1 of 2)
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 <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 row
17 [ 4, 5, 6 ] ]; // second row
18 var array2 = [ [ 1, 2 ], // first row
19 [ 3 ], // second row
20 [ 4, 5, 6 ] ]; // third row
21
22 outputArray( "Values in array1 by row", array1 );
23 outputArray( "Values in array2 by row", array2 );
24 }
Array array1 provides six initializers in
two rows.
Array array2 provides six initializers in
three rows.
Function outputArray displays each array’s
elements in a Web page.
InitArray3.html
(2 of 2)
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
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.
09/30/15 © Reem Al-Attas 55
Multidimensional Arrays
09/30/15 © Reem Al-Attas 56
Different array manipulations
using for and for/in
var total = 0;
for (var row = 0; row < a.length; ++row )
for (var col = 0; col < a[ row ].length; ++col )
total += a[ row ][ col ];
identical to
var total = 0;
for (var row in a )
for (var col in a[ row ] )
total += a[ row ][ col ];
Both statements total the elements of the array,
one row at a time
09/30/15 © Reem Al-Attas 57
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
Quiz.html
(1 of 2)
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 11.14: quiz.html -->
6 <!-- Online Quiz -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Online Quiz</title>
11
12 <script type = "text/JavaScript">
13
14 function checkAnswers()
15 {
16 // determine whether the answer is correct
17 if ( myQuiz.radiobutton[ 1 ].checked )
18 document.write( "Congratulations, your answer is correct" );
19 else // if the answer is incorrect
20 document.write( "Your answer is incorrect. Please try again" );
21 }
22
23 </script>
24
25 </head>
Determining the value of property
checked.
Quiz.html
(2 of 2)
26
27 <body>
28 <form id = "myQuiz" action = "JavaScript:checkAnswers()">
29 <p>Select the name of the tip that goes with the image shown:<br />
30 <img src="EPT.gif" width="108" height="100" alt="mystery tip"/>
31 <br />
32
33 <input type = "radio" name = "radiobutton" value = "CPE" />
34 <label>Common Programming Error</label>
35
36 <input type = "radio" name = "radiobutton" value = "EPT" />
37 <label>Error-Prevention Tip</label>
38
39 <input type = "radio" name = "radiobutton" value = "PERF" />
40 <label>Performance Tip</label>
41
42 <input type = "radio" name = "radiobutton" value = "PORT" />
43 <label>Portability Tip</label><br />
44
45 <input type = "submit" name = "submit" value = "Submit" />
46 <input type = "reset" name = "reset" value = "Reset" />
47 </p>
48 </form>
49 </body>
50 </html>
Call the checkAnswers function
when the form is submitted.
09/30/15 © Reem Al-Attas 60
Building an Online Quiz
09/30/15 © Reem Al-Attas 61
Assignment 9
 1) Exercise # 11.10. Due Date for A # 9:
 Next Monday before
your lecture.

More Related Content

What's hot

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
An introduction to bootstrap
An introduction to bootstrapAn introduction to bootstrap
An introduction to bootstrapMind IT Systems
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements IReem Alattas
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 

What's hot (20)

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
An introduction to bootstrap
An introduction to bootstrapAn introduction to bootstrap
An introduction to bootstrap
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements I
 
Jquery
JqueryJquery
Jquery
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Introduction to css
Introduction to cssIntroduction to css
Introduction to css
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Php array
Php arrayPhp array
Php array
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Css box-model
Css box-modelCss box-model
Css box-model
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 

Viewers also liked

Javascript - Array - Creating Array
Javascript - Array - Creating ArrayJavascript - Array - Creating Array
Javascript - Array - Creating ArraySamuel Santos
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsSolv AS
 
Working with Arrays in JavaScript
Working with Arrays in JavaScriptWorking with Arrays in JavaScript
Working with Arrays in JavaScriptFlorence Davis
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP Ajit Sinha
 
Javascript - Array - Writing
Javascript - Array - WritingJavascript - Array - Writing
Javascript - Array - WritingSamuel Santos
 
Cloud computing
Cloud computingCloud computing
Cloud computingAjit Sinha
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Shekhar Gulati
 
Javascript (parte 1)
Javascript (parte 1)Javascript (parte 1)
Javascript (parte 1)Alex Camargo
 
Html5 e css3 nei miei progetti: cosa ho fatto
Html5 e css3 nei miei progetti: cosa ho fattoHtml5 e css3 nei miei progetti: cosa ho fatto
Html5 e css3 nei miei progetti: cosa ho fattoRocco Passaro
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 
HTML5 e Css3 - 5 | WebMaster & WebDesigner
HTML5 e Css3 - 5 | WebMaster & WebDesignerHTML5 e Css3 - 5 | WebMaster & WebDesigner
HTML5 e Css3 - 5 | WebMaster & WebDesignerMatteo Magni
 

Viewers also liked (20)

Javascript - Array - Creating Array
Javascript - Array - Creating ArrayJavascript - Array - Creating Array
Javascript - Array - Creating Array
 
Javascript
JavascriptJavascript
Javascript
 
CSS
CSSCSS
CSS
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Working with Arrays in JavaScript
Working with Arrays in JavaScriptWorking with Arrays in JavaScript
Working with Arrays in JavaScript
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP
 
Javascript - Array - Writing
Javascript - Array - WritingJavascript - Array - Writing
Javascript - Array - Writing
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Arrays
ArraysArrays
Arrays
 
Print CSS
Print CSSPrint CSS
Print CSS
 
Corso HTML5. Esempi di App
Corso HTML5. Esempi di AppCorso HTML5. Esempi di App
Corso HTML5. Esempi di App
 
HTML5 Live
HTML5 LiveHTML5 Live
HTML5 Live
 
HTML5 for Mobile
HTML5 for MobileHTML5 for Mobile
HTML5 for Mobile
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud
 
Javascript (parte 1)
Javascript (parte 1)Javascript (parte 1)
Javascript (parte 1)
 
Html5 e css3 nei miei progetti: cosa ho fatto
Html5 e css3 nei miei progetti: cosa ho fattoHtml5 e css3 nei miei progetti: cosa ho fatto
Html5 e css3 nei miei progetti: cosa ho fatto
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
Ecommerce final
Ecommerce finalEcommerce final
Ecommerce final
 
HTML5 e Css3 - 5 | WebMaster & WebDesigner
HTML5 e Css3 - 5 | WebMaster & WebDesignerHTML5 e Css3 - 5 | WebMaster & WebDesigner
HTML5 e Css3 - 5 | WebMaster & WebDesigner
 

Similar to JavaScript Arrays Guide

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements IIReem Alattas
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XMLguest2556de
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1H K
 
Dynamic HTML Event Model
Dynamic HTML Event ModelDynamic HTML Event Model
Dynamic HTML Event ModelReem Alattas
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07HUST
 
Program 1 (Practicing an example of function using call by referenc.pdf
Program 1 (Practicing an example of function using call by referenc.pdfProgram 1 (Practicing an example of function using call by referenc.pdf
Program 1 (Practicing an example of function using call by referenc.pdfezhilvizhiyan
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfadmin463580
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202Mahmoud Samir Fayed
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)Make Mannan
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 

Similar to JavaScript Arrays Guide (20)

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements II
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
 
array
arrayarray
array
 
Dynamic HTML Event Model
Dynamic HTML Event ModelDynamic HTML Event Model
Dynamic HTML Event Model
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07
 
02 arrays
02 arrays02 arrays
02 arrays
 
Program 1 (Practicing an example of function using call by referenc.pdf
Program 1 (Practicing an example of function using call by referenc.pdfProgram 1 (Practicing an example of function using call by referenc.pdf
Program 1 (Practicing an example of function using call by referenc.pdf
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 

More from Reem Alattas

Rumble Lights Pitch Deck
Rumble Lights Pitch DeckRumble Lights Pitch Deck
Rumble Lights Pitch DeckReem Alattas
 
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular RobotsNASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular RobotsReem Alattas
 
She looks just like me 2017
She looks just like me 2017She looks just like me 2017
She looks just like me 2017Reem Alattas
 
Nasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space ExplorationNasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space ExplorationReem Alattas
 
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space ExplorationNasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space ExplorationReem Alattas
 
She Looks Just Like Me 2017
She Looks Just Like Me 2017She Looks Just Like Me 2017
She Looks Just Like Me 2017Reem Alattas
 
Evolutionary Algorithms
Evolutionary AlgorithmsEvolutionary Algorithms
Evolutionary AlgorithmsReem Alattas
 
Evolutionary Robotics
Evolutionary RoboticsEvolutionary Robotics
Evolutionary RoboticsReem Alattas
 
Enhancing input on and above the interactive surface
Enhancing input on and above the interactive surfaceEnhancing input on and above the interactive surface
Enhancing input on and above the interactive surfaceReem Alattas
 
Skinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input SurfaceSkinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input SurfaceReem Alattas
 
XML - EXtensible Markup Language
XML - EXtensible Markup LanguageXML - EXtensible Markup Language
XML - EXtensible Markup LanguageReem Alattas
 
DHTML - Dynamic HTML
DHTML - Dynamic HTMLDHTML - Dynamic HTML
DHTML - Dynamic HTMLReem Alattas
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary SearchReem Alattas
 
Cascading Style Sheet - CSS
Cascading Style Sheet - CSSCascading Style Sheet - CSS
Cascading Style Sheet - CSSReem Alattas
 
HTML tables- rowspan n colspan
HTML tables- rowspan n colspanHTML tables- rowspan n colspan
HTML tables- rowspan n colspanReem Alattas
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTMLReem Alattas
 

More from Reem Alattas (20)

Rumble Lights Pitch Deck
Rumble Lights Pitch DeckRumble Lights Pitch Deck
Rumble Lights Pitch Deck
 
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular RobotsNASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
 
She looks just like me 2017
She looks just like me 2017She looks just like me 2017
She looks just like me 2017
 
Nasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space ExplorationNasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space Exploration
 
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space ExplorationNasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
 
She Looks Just Like Me 2017
She Looks Just Like Me 2017She Looks Just Like Me 2017
She Looks Just Like Me 2017
 
Tran helmet pitch
Tran helmet pitchTran helmet pitch
Tran helmet pitch
 
Evolutionary Algorithms
Evolutionary AlgorithmsEvolutionary Algorithms
Evolutionary Algorithms
 
Evolutionary Robotics
Evolutionary RoboticsEvolutionary Robotics
Evolutionary Robotics
 
Create a Need
Create a NeedCreate a Need
Create a Need
 
Enhancing input on and above the interactive surface
Enhancing input on and above the interactive surfaceEnhancing input on and above the interactive surface
Enhancing input on and above the interactive surface
 
Skinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input SurfaceSkinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input Surface
 
XML - EXtensible Markup Language
XML - EXtensible Markup LanguageXML - EXtensible Markup Language
XML - EXtensible Markup Language
 
PHP Scripting
PHP ScriptingPHP Scripting
PHP Scripting
 
DHTML - Dynamic HTML
DHTML - Dynamic HTMLDHTML - Dynamic HTML
DHTML - Dynamic HTML
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Cascading Style Sheet - CSS
Cascading Style Sheet - CSSCascading Style Sheet - CSS
Cascading Style Sheet - CSS
 
HTML tables- rowspan n colspan
HTML tables- rowspan n colspanHTML tables- rowspan n colspan
HTML tables- rowspan n colspan
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 

Recently uploaded

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

JavaScript Arrays Guide

  • 1. IPA 1st Semester, 2007-2008 Internet 1 Ch. 12 JavaScript: Arrays attasr@ipa.edu.sa
  • 2. 09/30/15 © Reem Al-Attas 2 Introduction Arrays  Data structures of related items  Also called Collections  Dynamic
  • 3. 09/30/15 © Reem Al-Attas 3 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
  • 4. 09/30/15 © Reem Al-Attas 4 Arrays c[ 6 ] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array 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.
  • 5. 09/30/15 © Reem Al-Attas 5 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.
  • 6. 09/30/15 © Reem Al-Attas 6 Declaring and Allocating Arrays Arrays in memory  Objects  Operator new  Allocates memory for objects  Dynamic memory allocation operator var c; c = new Array( 12 );
  • 7. 09/30/15 © Reem Al-Attas 7 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
  • 8. 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 occurs 16 function initializeArrays() 17 { 18 var n1 = new Array( 5 ); // allocate 5-element Array 19 var n2 = new Array(); // allocate empty Array 20 21 // assign values to each element of Array n1 22 for ( var i = 0; i < n1.length; ++i ) 23 n1[ i ] = i; 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.
  • 9. 24 25 // create and initialize five-elements in Array n2 26 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 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>" ); 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. 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.
  • 10. 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>
  • 11. 09/30/15 © Reem Al-Attas 11 Examples Using Arrays
  • 12. 09/30/15 © Reem Al-Attas 12 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 ];
  • 13. 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 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 ]; 22 23 outputArray( "Array colors contains", colors ); 24 outputArray( "Array integers1 contains", integers1 ); 25 outputArray( "Array integers2 contains", integers2 ); 26 } Array integers1 is initialized using an initializer list. Two values are not supplied for integers2, which will be displayed as undefined.
  • 14. 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> 49 </html>
  • 15. 09/30/15 © Reem Al-Attas 15 Examples Using Arrays
  • 16. 09/30/15 © Reem Al-Attas 16 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
  • 17. SumArray.html (1 of 2) 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 The for loop sums the values contained in the 10- element integer array called theArray.
  • 18. 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> Variable element is assigned a subscript in the range of 0 up to, but not including, theArray.length.
  • 19. 09/30/15 © Reem Al-Attas 19 Examples Using Arrays
  • 20. 09/30/15 © Reem Al-Attas 20 Examples Using Arrays Arrays can provide shorter and cleaner substitute for switch statements  Each element represents one case
  • 21. RollDie.html (1 of 2) 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 results 17 for ( var roll = 1; roll <= 6000; ++roll ) { 18 face = Math.floor( 1 + Math.random() * 6 ); 19 ++frequency[ face ]; 20 } 21 Referencing Array frequency replaces the switch statement used in Chapter 10’s example.
  • 22. RollDie.html (2 of 2) 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> 40 </html>
  • 23. 09/30/15 © Reem Al-Attas 23 Examples Using Arrays
  • 24. 09/30/15 © Reem Al-Attas 24 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
  • 25. RandomPicture2 .html (1 of 2) 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"> 9 <head> 10 <title>Random Image Generator</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var pictures = 15 [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];
  • 26. RandomPicture2 .html (2 of 2) 16 17 document.write ( "<img src = "" + 18 pictures[ Math.floor( Math.random() * 7 ) ] + 19 ".gif" width = "105" height = "100" />" ); 20 // --> 21 </script> 22 23 </head> 24 25 <body> 26 <p>Click Refresh (or Reload) to run the script again</p> 27 </body> 28 </html>
  • 27. 09/30/15 © Reem Al-Attas 27 Random Image Generator Using Arrays
  • 28. 09/30/15 © Reem Al-Attas 28 References and Reference Parameters Two ways to pass parameters  Pass-by-value  Pass copy of original value  Default for numbers and booleans  Original variable is unchanged  Pass-by-reference  How objects are passed, like arrays  Pass location in memory of value  Allows direct access to original value  Improves performance
  • 29. 09/30/15 © Reem Al-Attas 29 Passing Arrays to Functions Name of array is argument  Not necessary to also pass size of array  Arrays know their size  Passed by reference  Individual elements are passed by value if numbers or booleans  Array.join  Creates string containing all array elements  Specify separator
  • 30. PassArray.html (1 of 3) 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: 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-reference 25 The first call to function outputArray displays the contents of the Array a before it is modified. Function modifyArray multiplies each element by 2.
  • 31. PassArray.html (2 of 3) 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 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 Again, function outputArray is called to show that the contents of Array a have been modified. 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. Function modifyElement multiplies the contents of a[ 3 ] by 2. The value of a[ 3 ] is output to show its contents before it is modified.
  • 32. PassArray.html (3 of 3) 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 ) 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> Multiply each element in theArray by 2.
  • 33. 09/30/15 © Reem Al-Attas 33 Passing Arrays to Functions
  • 34. 09/30/15 © Reem Al-Attas 34 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
  • 35. Sort.html (1 of 2) 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: 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 array 21 outputArray( "Data items in ascending order: ", a ); 22 } 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.
  • 36. Sort.html (2 of 2) 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 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // --> 37 </script> 38 39 </head><body onload = "start()"></body> 40 </html> Function compareIntegers calculates the difference between the integer values of its arguments.
  • 37. 09/30/15 © Reem Al-Attas 37 Sorting Arrays
  • 38. 09/30/15 © Reem Al-Attas 38 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
  • 39. LinearSearch.html (1 of 3) 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.10: 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 Array 15 16 // fill Array with even integer values from 0 to 198 17 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; 19 Array a is initiated with 100 elements. Array a is populated with the even integers 0 to 198.
  • 40. LinearSearch.html (2 of 3) 20 // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; 24 25 // 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 ) ); 29 30 if ( element != -1 ) 31 searchForm.result.value = 32 "Found value in element " + element; 33 else 34 searchForm.result.value = "Value not found"; 35 } 36 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.
  • 41. LinearSearch.html (3 of 3) 37 // 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; 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> 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.
  • 42. 09/30/15 © Reem Al-Attas 42 Searching Arrays: Linear Search and Binary Search
  • 43. BinarySearch.html (1 of 5) 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.11 : 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 Array a is initialized with 15 elements.
  • 44. BinarySearch.html (2 of 5) 19 // function called when "Search" button is pressed 20 function buttonPressed() 21 { 22 var searchKey = searchForm.inputVal.value; 23 24 searchForm.result.value = 25 "Portions of array searchedn"; 26 27 // 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 34 if ( element != -1 ) 35 searchForm.result.value += 36 "nFound value in element " + element; 37 else 38 searchForm.result.value += "nValue not found"; 39 } 40 Function binarySearch receives two arguments: the Array a and the search key, searchKey.
  • 45. BinarySearch.html (3 of 5) 41 // 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 47 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 ] ) // 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 } 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.
  • 46. BinarySearch.html (4 of 5) 64 65 return -1; // searchKey not found 66 } 67 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 < low || i > high ) 74 searchForm.result.value += " "; 75 // mark middle element in output 76 else if ( i == mid ) 77 searchForm.result.value += theArray[ i ] + 78 ( theArray[ i ] < 10 ? "* " : "* " ); 79 else 80 searchForm.result.value += theArray[ i ] + 81 ( theArray[ i ] < 10 ? " " : " " ); 82 } 83 84 searchForm.result.value += "n"; 85 } 86 // --> 87 </script> 88 </head> 89 Function buildOutput creates the markup that displays the results of the search.
  • 47. 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>
  • 48. 09/30/15 © Reem Al-Attas 48 Searching Arrays: Linear Search and Binary Search
  • 49. 09/30/15 © Reem Al-Attas 49 Multidimensional Arrays Two-dimensional arrays analogous to tables  Rows and columns  Specify row first, then column  Two subscripts
  • 50. 09/30/15 © Reem Al-Attas 50 Multidimensional 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.12 Two-dimensional array with three rows and four columns.
  • 51. 09/30/15 © Reem Al-Attas 51 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 ] ];
  • 52. 09/30/15 © Reem Al-Attas 52 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 );
  • 53. InitArray3.html (1 of 2) 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 <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 row 17 [ 4, 5, 6 ] ]; // second row 18 var array2 = [ [ 1, 2 ], // first row 19 [ 3 ], // second row 20 [ 4, 5, 6 ] ]; // third row 21 22 outputArray( "Values in array1 by row", array1 ); 23 outputArray( "Values in array2 by row", array2 ); 24 } Array array1 provides six initializers in two rows. Array array2 provides six initializers in three rows. Function outputArray displays each array’s elements in a Web page.
  • 54. InitArray3.html (2 of 2) 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 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.
  • 55. 09/30/15 © Reem Al-Attas 55 Multidimensional Arrays
  • 56. 09/30/15 © Reem Al-Attas 56 Different array manipulations using for and for/in var total = 0; for (var row = 0; row < a.length; ++row ) for (var col = 0; col < a[ row ].length; ++col ) total += a[ row ][ col ]; identical to var total = 0; for (var row in a ) for (var col in a[ row ] ) total += a[ row ][ col ]; Both statements total the elements of the array, one row at a time
  • 57. 09/30/15 © Reem Al-Attas 57 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
  • 58. Quiz.html (1 of 2) 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 11.14: quiz.html --> 6 <!-- Online Quiz --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Online Quiz</title> 11 12 <script type = "text/JavaScript"> 13 14 function checkAnswers() 15 { 16 // determine whether the answer is correct 17 if ( myQuiz.radiobutton[ 1 ].checked ) 18 document.write( "Congratulations, your answer is correct" ); 19 else // if the answer is incorrect 20 document.write( "Your answer is incorrect. Please try again" ); 21 } 22 23 </script> 24 25 </head> Determining the value of property checked.
  • 59. Quiz.html (2 of 2) 26 27 <body> 28 <form id = "myQuiz" action = "JavaScript:checkAnswers()"> 29 <p>Select the name of the tip that goes with the image shown:<br /> 30 <img src="EPT.gif" width="108" height="100" alt="mystery tip"/> 31 <br /> 32 33 <input type = "radio" name = "radiobutton" value = "CPE" /> 34 <label>Common Programming Error</label> 35 36 <input type = "radio" name = "radiobutton" value = "EPT" /> 37 <label>Error-Prevention Tip</label> 38 39 <input type = "radio" name = "radiobutton" value = "PERF" /> 40 <label>Performance Tip</label> 41 42 <input type = "radio" name = "radiobutton" value = "PORT" /> 43 <label>Portability Tip</label><br /> 44 45 <input type = "submit" name = "submit" value = "Submit" /> 46 <input type = "reset" name = "reset" value = "Reset" /> 47 </p> 48 </form> 49 </body> 50 </html> Call the checkAnswers function when the form is submitted.
  • 60. 09/30/15 © Reem Al-Attas 60 Building an Online Quiz
  • 61. 09/30/15 © Reem Al-Attas 61 Assignment 9  1) Exercise # 11.10. Due Date for A # 9:  Next Monday before your lecture.