31
1 2008 Pearson Education, Inc. All rights reserved. 1 10 10 JavaScript: Arrays 2008 Pearson Education, Inc. All rights reserved. 2 10.1 Introduction Arrays Data structures consisting of related data items Sometimes called collections of data items JavaScript arrays “dynamic” entities that can change size after they are created

10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

  • Upload
    others

  • View
    18

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

1

� 2008 Pearson Education, Inc. All rights reserved.

1

1010

JavaScript: Arrays

� 2008 Pearson Education, Inc. All rights reserved.

2

10.1 Introduction

• Arrays

– Data structures consisting of related data items

– Sometimes called collections of data items

• JavaScript arrays

– “dynamic” entities that can change size after they are

created

Page 2: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

2

� 2008 Pearson Education, Inc. All rights reserved.

3

10.2 Arrays

• An array is a group of memory locations

– All have the same name and normally are of the same type

(although this attribute is not required in JavaScript)

• Each individual location is called an element

• An element may be referred to by giving the

name of the array followed by index of the

element in square brackets ([][][][])

� 2008 Pearson Education, Inc. All rights reserved.

4

10.2 Arrays (Cont.)

• The first element in every array is the zeroth element.

• The ith element of array cccc is referred to as c[ic[ic[ic[i----1]1]1]1].

• Array names follow the same conventions as other identifiers

• A subscripted array name

– can be used on the left side of an assignment to place a new value into an array element

– can be used on the right side of an assignment operation to use its value

• Every array in JavaScript knows its own length, which it stores in its lengthlengthlengthlength attribute and can be found with the expression arraynamearraynamearraynamearrayname.length.length.length.length

Page 3: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

3

� 2008 Pearson Education, Inc. All rights reserved.

5

Fig. 10.1 | Array with 12 elements.

� 2008 Pearson Education, Inc. All rights reserved.

6

Common Programming Error 10.1

It is important to note the difference between the “seventh element of the array” and “array element seven.” Because array subscripts begin at 0, the seventh element of the array has a subscript of 6, while array element seven has a subscript of 7 and is actually the eighth element of the array. This confusion is a source of “off-by-one” errors.

Page 4: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

4

� 2008 Pearson Education,

Inc. All rights reserved.

7

Fig. 10.2 |

Precedence and

associativity of

the operators

discussed so

far.

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

� 2008 Pearson Education, Inc. All rights reserved.

8

10.3 Declaring and Allocating Arrays

• JavaScript arrays are ArrayArrayArrayArray objects.

• Creating new objects using the newnewnewnew operator is known as creating an instance or instantiating an

object

• Operator newnewnewnew is known as the dynamic memory allocation operator

Page 5: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

5

� 2008 Pearson Education, Inc. All rights reserved.

9

Common Programming Error 10.2

Assuming that the elements of an array are initialized when the array is allocated may result in logic errors.

� 2008 Pearson Education, Inc. All rights reserved.

10

10.4 Examples Using Arrays

• Zero-based counting is usually used to iterate

through arrays

• JavaScript reallocates an ArrayArrayArrayArray when a value is assigned to an element that is outside the bounds

of the original ArrayArrayArrayArray

• Elements between the last element of the original

ArrayArrayArrayArray and the new element have undefined values

Page 6: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

6

� 2008 Pearson Education,

Inc. All rights reserved.

11

Fig. 10.3 |

Initializing the

elements of an

array (Part 1 of

3).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.3: InitArray.html 10.3: InitArray.html 10.3: InitArray.html 10.3: InitArray.html -------->>>>

6 <!<!<!<!-------- Initializing the elements of an arraInitializing the elements of an arraInitializing the elements of an arraInitializing the elements of an array. y. y. y. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Initializing an ArrayInitializing an ArrayInitializing an ArrayInitializing an Array</title></title></title></title>

10 <style type = <style type = <style type = <style type = "text/css""text/css""text/css""text/css">>>>

11 tabletabletabletable { { { { width:width:width:width: 10em10em10em10em }}}}

12 thththth { { { { texttexttexttext----align:align:align:align: leftleftleftleft }}}}

13 </style></style></style></style>

14 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

15 <!<!<!<!--------

16 // create (declare) two new arrays// create (declare) two new arrays// create (declare) two new arrays// create (declare) two new arrays

17 varvarvarvar n1 = n1 = n1 = n1 = newnewnewnew Array( Array( Array( Array( 5555 ); ); ); ); // allocate five// allocate five// allocate five// allocate five----element Arrayelement Arrayelement Arrayelement Array

18 varvarvarvar n2 = n2 = n2 = n2 = newnewnewnew Array(); Array(); Array(); Array(); // allocate empty Array// allocate empty Array// allocate empty Array// allocate empty Array

19

20 // assign values to each element of Array n1 // assign values to each element of Array n1 // assign values to each element of Array n1 // assign values to each element of Array n1

21 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < n1.length; ++i ) ; i < n1.length; ++i ) ; i < n1.length; ++i ) ; i < n1.length; ++i )

22 n1[ i ] = i;n1[ i ] = i;n1[ i ] = i;n1[ i ] = i;

23

24 // create and initialize fiv// create and initialize fiv// create and initialize fiv// create and initialize five elements in Array n2e elements in Array n2e elements in Array n2e elements in Array n2

25 forforforfor ( i = ( i = ( i = ( i = 0000; i < ; i < ; i < ; i < 5555; ++i ); ++i ); ++i ); ++i )

26 n2[ i ] = i;n2[ i ] = i;n2[ i ] = i;n2[ i ] = i;

27

28 outputArray( outputArray( outputArray( outputArray( "Array n1:""Array n1:""Array n1:""Array n1:", n1 );, n1 );, n1 );, n1 );

29 outputArray( outputArray( outputArray( outputArray( "Array n2:""Array n2:""Array n2:""Array n2:", n2 );, n2 );, n2 );, n2 );

30

Operator new allocates

an Array called n1 with

five elements

Operator new allocates an

empty Array called n2

Zero-based counting used in

for loop to set each element’s

value equal to its subscript

Five elements added and

initialized in n2, which

dynamically expands

� 2008 Pearson Education,

Inc. All rights reserved.

12

Fig. 10.3 |

Initializing the

elements of an

array (Part 2 of

3).

31 // output the heading followed by a two// output the heading followed by a two// output the heading followed by a two// output the heading followed by a two----column table column table column table column table

32 // containing subscripts and elements of "theArray" // containing subscripts and elements of "theArray" // containing subscripts and elements of "theArray" // containing subscripts and elements of "theArray"

33 functionfunctionfunctionfunction outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )

34 {{{{

35 document.writeln( document.writeln( document.writeln( document.writeln( "<h2>""<h2>""<h2>""<h2>" + headi+ headi+ headi+ heading + ng + ng + ng + "</h2>" "</h2>" "</h2>" "</h2>" ););););

36 document.writeln( document.writeln( document.writeln( document.writeln( "<table border = "<table border = "<table border = "<table border = \\\\"1"1"1"1\\\\"" "" "" "" ););););

37 document.writeln( document.writeln( document.writeln( document.writeln( "<thead><th>Subscript</th>""<thead><th>Subscript</th>""<thead><th>Subscript</th>""<thead><th>Subscript</th>" ++++

38 "<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>" ); ); ); );

39

40 // output the subscript and val// output the subscript and val// output the subscript and val// output the subscript and value of each array elementue of each array elementue of each array elementue of each array element

41 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ )

42 document.writeln( document.writeln( document.writeln( document.writeln( "<tr><td>""<tr><td>""<tr><td>""<tr><td>" + i ++ i ++ i ++ i + "</td><td>""</td><td>""</td><td>""</td><td>" ++++

43 theArray[ i ] + theArray[ i ] + theArray[ i ] + theArray[ i ] + "</td></tr>""</td></tr>""</td></tr>""</td></tr>" ););););

44

45 ddddocument.writeln(ocument.writeln(ocument.writeln(ocument.writeln( "</tbody></table>" "</tbody></table>" "</tbody></table>" "</tbody></table>" ););););

46 }}}} // end function outputArray// end function outputArray// end function outputArray// end function outputArray

47 // // // // -------->>>>

48 </script></script></script></script>

49 </head><body></body></head><body></body></head><body></body></head><body></body>

50 </html></html></html></html>

Outputs the subscript and value

of every array element in a table

Page 7: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

7

� 2008 Pearson Education, Inc. All rights reserved.

13

Fig. 10.3 | Initializing the elements of an array (Part 3 of 3).

� 2008 Pearson Education, Inc. All rights reserved.

14

Software Engineering Observation 10.1

JavaScript automatically reallocates an ArrayArrayArrayArraywhen a value is assigned to an element that is outside the bounds of the original ArrayArrayArrayArray . Elements between the last element of the original ArrayArrayArrayArray and the new element have undefined values.

Page 8: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

8

� 2008 Pearson Education, Inc. All rights reserved.

15

Common Programming Error 10.3

Referring to an element outside the ArrayArrayArrayArraybounds is normally a logic error.

� 2008 Pearson Education, Inc. All rights reserved.

16

Error-Prevention Tip 10.1

When using subscripts to loop through an ArrayArrayArrayArray, the subscript should never go below 0 and should always be less than the number of elements in the ArrayArrayArrayArray (i.e., one less than the size of the ArrayArrayArrayArray ). Make sure that the loop-terminating condition prevents the access of elements outside this range.

Page 9: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

9

� 2008 Pearson Education, Inc. All rights reserved.

17

10.4 Examples Using Arrays (Cont.)

• Arrays can be created using a comma-separated

initializer list enclosed in square brackets ([][][][])

– The array’s size is determined by the number of values in

the initializer list

• The initial values of an array can be specified as

arguments in the parentheses following newnewnewnewArrayArrayArrayArray– The size of the array is determined by the number of

values in parentheses

� 2008 Pearson Education,

Inc. All rights reserved.

18

Fig. 10.4 |

Declaring and

initializing

arrays (Part 1 of

3).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.4: InitArray2.html 10.4: InitArray2.html 10.4: InitArray2.html 10.4: InitArray2.html -------->>>>

6 <!<!<!<!-------- Declaring and initializing arrays. Declaring and initializing arrays. Declaring and initializing arrays. Declaring and initializing arrays. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Initializing an Array with a DeclarationInitializing an Array with a DeclarationInitializing an Array with a DeclarationInitializing an Array with a Declaration</title></title></title></title>

10 <style type = <style type = <style type = <style type = "text/css""text/css""text/css""text/css">>>>

11 tabletabletabletable { { { { width:width:width:width: 15em15em15em15em }}}}

12 thththth { { { { texttexttexttext----align:align:align:align: leftleftleftleft }}}}

13 </style></style></style></style>

14 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

15 <!<!<!<!--------

16 // Initializer list specifies the number of elements and// Initializer list specifies the number of elements and// Initializer list specifies the number of elements and// Initializer list specifies the number of elements and

17 // a value for each element.// a value for each element.// a value for each element.// a value for each element.

18 varvarvarvar colors = colors = colors = colors = newnewnewnew Array( Array( Array( Array( "cyan""cyan""cyan""cyan", , , , "magenta""magenta""magenta""magenta",,,,"yellow""yellow""yellow""yellow",,,, "black""black""black""black" ););););

19 varvarvarvar integers1 = [ integers1 = [ integers1 = [ integers1 = [ 2222, , , , 4444, , , , 6666, , , , 8888 ];];];];

20 varvarvarvar integers2 = [ integers2 = [ integers2 = [ integers2 = [ 2222, , , , , , , , , , , , 8888 ];];];];

21

22 outputArray( outputArray( outputArray( outputArray( "Array colors contains""Array colors contains""Array colors contains""Array colors contains", colors );, colors );, colors );, colors );

23 outoutoutoutputArray( putArray( putArray( putArray( "Array integers1 contains""Array integers1 contains""Array integers1 contains""Array integers1 contains", integers1 );, integers1 );, integers1 );, integers1 );

24 outputArray( outputArray( outputArray( outputArray( "Array integers2 contains""Array integers2 contains""Array integers2 contains""Array integers2 contains", integers2 );, integers2 );, integers2 );, integers2 );

25

26 // output the heading followed by a two// output the heading followed by a two// output the heading followed by a two// output the heading followed by a two----column table column table column table column table

27 // containing the subscripts and elements of t// containing the subscripts and elements of t// containing the subscripts and elements of t// containing the subscripts and elements of theArray heArray heArray heArray

28 functionfunctionfunctionfunction outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )

29 {{{{

Creates an array with four

elements, all of which are

defined

Creates an array with four

elements, all of which are

defined in an initializer list

Creates an array with four

elements, two of which reserve

space for values to be specified

later

Page 10: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

10

� 2008 Pearson Education,

Inc. All rights reserved.

19

Fig. 10.4 |

Declaring and

initializing

arrays (Part 2 of

3).

30 document.writeln( document.writeln( document.writeln( document.writeln( "<h2>""<h2>""<h2>""<h2>" + heading + + heading + + heading + + heading + "</h2>""</h2>""</h2>""</h2>" ); ); ); );

31 document.writeln( document.writeln( document.writeln( document.writeln( "<table border = "<table border = "<table border = "<table border = \\\\"1"1"1"1\\\\"""""""" ); ); ); );

32 document.writeln( document.writeln( document.writeln( document.writeln( "<thead><th>Subscript</th>" "<thead><th>Subscript</th>" "<thead><th>Subscript</th>" "<thead><th>Subscript</th>" ++++

33 "<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>""<th>Value</th></thead><tbody>" ); ); ); );

34

35 // output the subscript and value of each array element // output the subscript and value of each array element // output the subscript and value of each array element // output the subscript and value of each array element

36 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < theArray.length; i++ ) ; i < theArray.length; i++ ) ; i < theArray.length; i++ ) ; i < theArray.length; i++ )

37 document.writeln( document.writeln( document.writeln( document.writeln( "<tr><td>""<tr><td>""<tr><td>""<tr><td>" + i + + i + + i + + i + "</td><td>" "</td><td>" "</td><td>" "</td><td>" + + + +

38 theArray[ i ] + theArray[ i ] + theArray[ i ] + theArray[ i ] + "</td></tr>" "</td></tr>" "</td></tr>" "</td></tr>" ););););

39

40 document.writeln( document.writeln( document.writeln( document.writeln( "</tbody></table>""</tbody></table>""</tbody></table>""</tbody></table>" ); ); ); );

41 } } } } // end function outputArray// end function outputArray// end function outputArray// end function outputArray

42 // // // // -------->>>>

43 </script> </script> </script> </script>

44 </head><body></body> </head><body></body> </head><body></body> </head><body></body>

45 </html></html></html></html>

� 2008 Pearson Education, Inc. All rights reserved.

20

Fig. 10.4 | Declaring and initializing arrays (Part 3 of 3).

Page 11: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

11

� 2008 Pearson Education, Inc. All rights reserved.

21

10.4 Examples Using Arrays (Cont.)

•forforforfor…………inininin statement– Enables a script to perform a task for each element in an array

– Process is known as iterating over the elements of an array

� 2008 Pearson Education,

Inc. All rights reserved.

22

Fig. 10.5 |

Summing

elements of an

array (Part 1 of

2).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.5: SumArray.html 10.5: SumArray.html 10.5: SumArray.html 10.5: SumArray.html -------->>>>

6 <!<!<!<!-------- Summing elements of an array. Summing elements of an array. Summing elements of an array. Summing elements of an array. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Sum the Elements of an ArraySum the Elements of an ArraySum the Elements of an ArraySum the Elements of an Array</title></title></title></title>

10

11 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

12 <!<!<!<!--------

13 varvarvarvar theArray = [ theArray = [ theArray = [ theArray = [ 1111, , , , 2222, , , , 3333, , , , 4444, , , , 5555, , , , 6666, , , , 7777, , , , 8888, , , , 9999, , , , 10101010 ];];];];

14 varvarvarvar total1 = total1 = total1 = total1 = 0000, total2 = , total2 = , total2 = , total2 = 0000;;;;

15

16 // iterates through the elements of the array in order and adds// iterates through the elements of the array in order and adds// iterates through the elements of the array in order and adds// iterates through the elements of the array in order and adds

17 // each element's value to total1// each element's value to total1// each element's value to total1// each element's value to total1

18 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ )

19 total1 += thtotal1 += thtotal1 += thtotal1 += theArray[ i ];eArray[ i ];eArray[ i ];eArray[ i ];

20

21 document.writeln( document.writeln( document.writeln( document.writeln( "Total using subscripts: ""Total using subscripts: ""Total using subscripts: ""Total using subscripts: " + total1 );+ total1 );+ total1 );+ total1 );

22

23 // iterates through the elements of the array using a for... in// iterates through the elements of the array using a for... in// iterates through the elements of the array using a for... in// iterates through the elements of the array using a for... in

24 // statement to add each element's value to tota// statement to add each element's value to tota// statement to add each element's value to tota// statement to add each element's value to total2l2l2l2

25 forforforfor ( ( ( ( varvarvarvar element element element element inininin theArray )theArray )theArray )theArray )

26 total2 += theArray[ element ];total2 += theArray[ element ];total2 += theArray[ element ];total2 += theArray[ element ];

Sums the values of all the

elements in theArrayby iterating through the

elements in order

Sums the values of all the

elements in theArray by

having JavaScript automatically

iterate over its elements

Page 12: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

12

� 2008 Pearson Education,

Inc. All rights reserved.

23

Fig. 10.5 |

Summing

elements of an

array (Part 2 of

2).

27

28 document.writeln( document.writeln( document.writeln( document.writeln( "<br />Total using for...in: ""<br />Total using for...in: ""<br />Total using for...in: ""<br />Total using for...in: " + total2 ); + total2 ); + total2 ); + total2 );

29 // // // // -------->>>>

30 </script> </script> </script> </script>

31 </head><body></body> </head><body></body> </head><body></body> </head><body></body>

32 </html></html></html></html>

� 2008 Pearson Education, Inc. All rights reserved.

24

Error-Prevention Tip 10.2

When iterating over all the elements of an ArrayArrayArrayArray, use a forforforfor…inininin statement to ensure that you manipulate only the existing elements of the ArrayArrayArrayArray. Note that a forforforfor…inininin statement skips any undefined elements in the array.

Page 13: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

13

� 2008 Pearson Education,

Inc. All rights reserved.

25

Fig. 10.6 | Dice-

rolling program

using an array

instead of a switchswitchswitchswitch (Part 1 of

2).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.6: RollDie.html 10.6: RollDie.html 10.6: RollDie.html 10.6: RollDie.html -------->>>>

6 <!<!<!<!-------- DiceDiceDiceDice----rolling program using an array inrolling program using an array inrolling program using an array inrolling program using an array instead of a switch. stead of a switch. stead of a switch. stead of a switch. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Roll a SixRoll a SixRoll a SixRoll a Six----Sided Die 6000 TimesSided Die 6000 TimesSided Die 6000 TimesSided Die 6000 Times</title> </title> </title> </title>

10 <style type = <style type = <style type = <style type = "text/css""text/css""text/css""text/css">>>>

11 tabletabletabletable { { { { width:width:width:width: 15em15em15em15em }}}}

12 thththth { { { { texttexttexttext----align:align:align:align: leftleftleftleft }}}}

13 </style></style></style></style>

14 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

15 <!<!<!<!--------

16 varvarvarvar face; face; face; face;

17 varvarvarvar frequency = [ , frequency = [ , frequency = [ , frequency = [ , 0000, , , , 0000, , , , 0000, , , , 0000, , , , 0000, , , , 0000 ]; ]; ]; ]; // leave frequency[0] // leave frequency[0] // leave frequency[0] // leave frequency[0]

18 // un// un// un// uninitializedinitializedinitializedinitialized

19

20 // summarize results// summarize results// summarize results// summarize results

21 forforforfor ( ( ( ( varvarvarvar roll = roll = roll = roll = 1111; roll <= ; roll <= ; roll <= ; roll <= 6000600060006000; ++roll ); ++roll ); ++roll ); ++roll )

22 {{{{

23 face = Math.floor( face = Math.floor( face = Math.floor( face = Math.floor( 1111 + Math.random() * + Math.random() * + Math.random() * + Math.random() * 6666 ););););

24 ++frequency[ face ];++frequency[ face ];++frequency[ face ];++frequency[ face ];

25 } } } } // end for// end for// end for// end for

26

27 document.writeln( document.writeln( document.writeln( document.writeln( "<table border = "<table border = "<table border = "<table border = \\\\"1"1"1"1\\\\"><thead>" "><thead>" "><thead>" "><thead>" ););););

28 document.writeln(document.writeln(document.writeln(document.writeln( "<th>Face</th>""<th>Face</th>""<th>Face</th>""<th>Face</th>" + + + +

29 "<th>Frequency</th></thead><tbody>" "<th>Frequency</th></thead><tbody>" "<th>Frequency</th></thead><tbody>" "<th>Frequency</th></thead><tbody>" ););););

30

Randomly picks a face of the die

and increments the value of the

element with the corresponding

index in the frequency array

Creates a frequency array with

each element’s index

corresponding to a face value (we

leave index 0 uninitialized because

the lowest face value is 1)

� 2008 Pearson Education,

Inc. All rights reserved.

26

Fig. 10.6 | Dice-

rolling program

using an array

instead of a switchswitchswitchswitch (Part 2 of

2).

31 // generate entire table of frequencies for each face// generate entire table of frequencies for each face// generate entire table of frequencies for each face// generate entire table of frequencies for each face

32 forforforfor ( face = ( face = ( face = ( face = 1111; face < frequency.length; ++face ); face < frequency.length; ++face ); face < frequency.length; ++face ); face < frequency.length; ++face )

33 document.writeln( document.writeln( document.writeln( document.writeln( "<tr><td>""<tr><td>""<tr><td>""<tr><td>" + face + + face + + face + + face + "</td><td>""</td><td>""</td><td>""</td><td>" ++++

34 frequency[ face ] + frequency[ face ] + frequency[ face ] + frequency[ face ] + "</td></t"</td></t"</td></t"</td></tr>" r>" r>" r>" ););););

35

36 document.writeln( document.writeln( document.writeln( document.writeln( "</tbody></table>" "</tbody></table>" "</tbody></table>" "</tbody></table>" ););););

37 // // // // -------->>>>

38 </script></script></script></script>

39 </head></head></head></head>

40 <body><body><body><body>

41 <p><p><p><p>Click Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script again</p></p></p></p>

42 </body></body></body></body>

43 </html></html></html></html>

Outputs results in a table

Page 14: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

14

� 2008 Pearson Education, Inc. All rights reserved.

27

10.5 Random Image Generator Using

Arrays

• Random image generator– Uses a pictures array to store the names of the image files as strings

– Accesses the array using a randomized index

� 2008 Pearson Education,

Inc. All rights reserved.

28

Fig. 10.7 |

Random image

generation

using arrays

(Part 1 of 2).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.7: RandomPicture2.html 10.7: RandomPicture2.html 10.7: RandomPicture2.html 10.7: RandomPicture2.html -------->>>>

6 <!<!<!<!-------- Random image generation using aRandom image generation using aRandom image generation using aRandom image generation using arrays. rrays. rrays. rrays. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Random Image GeneratorRandom Image GeneratorRandom Image GeneratorRandom Image Generator</title> </title> </title> </title>

10 <style type = <style type = <style type = <style type = "text/css""text/css""text/css""text/css">>>>

11 tabletabletabletable { { { { width:width:width:width: 15em15em15em15em }}}}

12 thththth { { { { texttexttexttext----align:align:align:align: leftleftleftleft }}}}

13 </style</style</style</style>>>>

14 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

15 <!<!<!<!--------

16 varvarvarvar pictures =pictures =pictures =pictures =

17 [ [ [ [ "CPE""CPE""CPE""CPE", , , , "EPT""EPT""EPT""EPT", , , , "GPP""GPP""GPP""GPP", , , , "GUI""GUI""GUI""GUI", , , , "PERF""PERF""PERF""PERF", , , , "PORT""PORT""PORT""PORT", , , , "SEO""SEO""SEO""SEO" ];];];];

18

19 // pick a random image fr// pick a random image fr// pick a random image fr// pick a random image from the pictures array and displays byom the pictures array and displays byom the pictures array and displays byom the pictures array and displays by

20 // creating an img tag and appending the src attribute to the // creating an img tag and appending the src attribute to the // creating an img tag and appending the src attribute to the // creating an img tag and appending the src attribute to the

21 // filename// filename// filename// filename

22 document.writedocument.writedocument.writedocument.write ( "<img src = "<img src = "<img src = "<img src = \\\\"""""""" +

23 pictures[ Math.floorpictures[ Math.floorpictures[ Math.floorpictures[ Math.floor( Math.random() * ( Math.random() * ( Math.random() * ( Math.random() * 7777 ) ] + ) ] + ) ] + ) ] + ".gif".gif".gif".gif\\\\" />"" />"" />"" />" ););););

24 // // // // -------->>>>

25 </script></script></script></script>

26 </head></head></head></head>

27 <body><body><body><body>

28 <p><p><p><p>Click Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script againClick Refresh (or Reload) to run the script again</p></p></p></p>

29 </body></body></body></body>

30 </html></html></html></html>

Creates an array with the names

of the images to choose from

Randomly selects an element

from the array and appends

its value to “.gif\” to

create the src attribute’s

value

Page 15: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

15

� 2008 Pearson Education, Inc. All rights reserved.

29

Fig. 10.7 | Random image generation using arrays (Part 2 of 2).

� 2008 Pearson Education, Inc. All rights reserved.

30

10.6 References and Reference

Parameters

• Two ways to pass arguments to functions (or methods)– pass-by-value

– pass-by-reference

• Pass-by-value– a copy of the argument’s value is made and is passed to the called function

• In JavaScript, numbers, boolean values and strings are passed to

functions by value.

• Pass-by-reference– The caller gives the called function direct access to the caller’s data and allows it to modify

the data if it so chooses

– Can improve performance because it can eliminate the overhead of copying large amounts of

data, but it can weaken security because the called function can access the caller’s data

Page 16: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

16

� 2008 Pearson Education, Inc. All rights reserved.

31

10.6 References and Reference

Parameters (Cont.)

• All objects are passed to functions by reference

• Arrays are objects in JavaScript, so ArrayArrayArrayArrays are passed toa function by reference– a called function can access the elements of the caller’s original ArrayArrayArrayArrays.

• Name of an array– actually a reference to an object that contains the array elements and

the lengthlengthlengthlength variable

� 2008 Pearson Education, Inc. All rights reserved.

32

Error-Prevention Tip 10.3

With pass-by-value, changes to the copy of the called function do not affect the original variable’s value in the calling function. This prevents the accidental side effects that so greatly hinder the development of correct and reliable software systems.

Page 17: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

17

� 2008 Pearson Education, Inc. All rights reserved.

33

Software Engineering Observation 10.2

Unlike some other languages, JavaScript does not allow the programmer to choose whether to pass each argument by value or by reference. Numbers, boolean values and strings are passed by value. Objects are passed to functions by reference. When a function receives a reference to an object, the function can manipulate the object directly.

� 2008 Pearson Education, Inc. All rights reserved.

34

Software Engineering Observation 10.3

When returning information from a function via a returnreturnreturnreturn statement, numbers and boolean values are always returned by value (i.e., a copy is returned), and objects are always returned by reference (i.e., a reference to the object is returned). Note that, in the pass-by-reference case, it is not necessary to return the new value, since the object is already modified.

Page 18: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

18

� 2008 Pearson Education, Inc. All rights reserved.

35

10.7 Passing Arrays to Functions

• Pass an array as an argument to a function– Specify the name of the array (a reference to the array) without brackets

• Although entire arrays are passed by reference, individual numeric

and boolean array elements are passed by value exactly as simple

numeric and boolean variables are passed– Such simple single pieces of data are called scalars, or scalar quantities

– To pass an array element to a function, use the subscripted name of the element as an

argument in the function call

• joinjoinjoinjoinmethod of an ArrayArrayArrayArray– Returns a string that contains all of the elements of an array, separated by the string

supplied in the function’s argument

– If an argument is not specified, the empty string is used as the separator

� 2008 Pearson Education,

Inc. All rights reserved.

36

Fig. 10.8 |

Passing arrays

and individual

array elements

to functions

(Part 1 of 3).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.8: PassArray.html 10.8: PassArray.html 10.8: PassArray.html 10.8: PassArray.html -------->>>>

6 <!<!<!<!-------- Passing arrays and individual array Passing arrays and individual array Passing arrays and individual array Passing arrays and individual array elements to functions. elements to functions. elements to functions. elements to functions. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Passing arrays and individual array Passing arrays and individual array Passing arrays and individual array Passing arrays and individual array

10 elements to functionselements to functionselements to functionselements to functions</title></title></title></title>

11 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

12 <!<!<!<!--------

13 varvarvarvar a = [ a = [ a = [ a = [ 1111, , , , 2222, , , , 3333, , , , 4444, , , , 5555 ];];];];

14

15 document.writeln(document.writeln(document.writeln(document.writeln( "<h2>Effects of passing entire ""<h2>Effects of passing entire ""<h2>Effects of passing entire ""<h2>Effects of passing entire " + + + +

16 "array by reference</h2>""array by reference</h2>""array by reference</h2>""array by reference</h2>" ););););

17 outputArray( outputArray( outputArray( outputArray( "Original array: ""Original array: ""Original array: ""Original array: ", a );, a );, a );, a );

18

19 modifyArray( a );modifyArray( a );modifyArray( a );modifyArray( a ); // array a passed by reference// array a passed by reference// array a passed by reference// array a passed by reference

20

21 outputArray( outputArray( outputArray( outputArray( "Modified array: ""Modified array: ""Modified array: ""Modified array: ", a );, a );, a );, a );

22

23 document.writeln( document.writeln( document.writeln( document.writeln( "<h2>Effects of passing array " "<h2>Effects of passing array " "<h2>Effects of passing array " "<h2>Effects of passing array " + + + +

24 "element by value</h2>""element by value</h2>""element by value</h2>""element by value</h2>" + + + +

25 "a[3] before modifyEle"a[3] before modifyEle"a[3] before modifyEle"a[3] before modifyElement: " ment: " ment: " ment: " + a[ + a[ + a[ + a[ 3333 ] );] );] );] );

26

27 modifyElement( a[ modifyElement( a[ modifyElement( a[ modifyElement( a[ 3333 ] ); ] ); ] ); ] ); // array element a[3] passed by value// array element a[3] passed by value// array element a[3] passed by value// array element a[3] passed by value

28

29 document.writeln( document.writeln( document.writeln( document.writeln( "<br />a[3] after modifyElement: ""<br />a[3] after modifyElement: ""<br />a[3] after modifyElement: ""<br />a[3] after modifyElement: " + a[ + a[ + a[ + a[ 3333 ] );] );] );] );

30

Passes array a to function

modifyArray by reference

Passes array element a[3] to

function modifyElement by

value

Page 19: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

19

� 2008 Pearson Education,

Inc. All rights reserved.

37

Fig. 10.8 |

Passing arrays

and individual

array elements

to functions

(Part 2 of 3).

31 // outputs heading followed by the contents of "theArray"// outputs heading followed by the contents of "theArray"// outputs heading followed by the contents of "theArray"// outputs heading followed by the contents of "theArray"

32 functionfunctionfunctionfunction outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )

33 {{{{

34 document.writeln( document.writeln( document.writeln( document.writeln(

35 heading + heading + heading + heading + theArray.join( theArray.join( theArray.join( theArray.join( " " " " " " " " )))) + + + + "<br />""<br />""<br />""<br />" ); ); ); );

36 } } } } // end function outputArray// end function outputArray// end function outputArray// end function outputArray

37

38 // function that modifies the elements of an array// function that modifies the elements of an array// function that modifies the elements of an array// function that modifies the elements of an array

39 functionfunctionfunctionfunction modifyArray( theArray )modifyArray( theArray )modifyArray( theArray )modifyArray( theArray )

40 {{{{

41 forforforfor ( ( ( ( varvarvarvar j j j j inininin theArray )theArray )theArray )theArray )

42 theArray[ j ] *= theArray[ j ] *= theArray[ j ] *= theArray[ j ] *= 2222;;;;

43 }}}} // end function modifyArray// end function modifyArray// end function modifyArray// end function modifyArray

44

45 // function that modifies the value passed // function that modifies the value passed // function that modifies the value passed // function that modifies the value passed

46 functionfunctionfunctionfunction modifyElement( e )modifyElement( e )modifyElement( e )modifyElement( e )

47 {{{{

48 e *= 2; e *= 2; e *= 2; e *= 2; // scales element e only for the duration of the// scales element e only for the duration of the// scales element e only for the duration of the// scales element e only for the duration of the

49 // function// function// function// function

50 document.writeln( document.writeln( document.writeln( document.writeln( "<br />value in modifyElement: " "<br />value in modifyElement: " "<br />value in modifyElement: " "<br />value in modifyElement: " + e );+ e );+ e );+ e );

51 } } } } // end function modifyElement// end function modifyElement// end function modifyElement// end function modifyElement

52 // // // // -------->>>>

53 </script></script></script></script>

54 </head><body></body></head><body></body></head><body></body></head><body></body>

55 </html></html></html></html>

Creates a string

containing all the

elements in

theArray,

separated by “ ”

Multiplies each element in

theArray by 2, which persists

after the function has finished

Multiplies the array element

by 2, but only for the duration

of the function

� 2008 Pearson Education, Inc. All rights reserved.

38

Fig. 10.8 | Passing arrays and individual array elements to functions (Part 3 of 3).

Page 20: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

20

� 2008 Pearson Education, Inc. All rights reserved.

39

Software Engineering Observation 10.4

JavaScript does not check the number of arguments or types of arguments that are passed to a function. It is possible to pass any number of values to a function. JavaScript will attempt to perform conversions when the values are used.

� 2008 Pearson Education, Inc. All rights reserved.

40

10.8 Sorting Arrays

• Sorting data– Putting data in a particular order, such as ascending or descending

– One of the most important computing functions

• ArrayArrayArrayArray object in JavaScript has a built-in method sortsortsortsort– With no arguments, the method uses string comparisons to determine the sorting order of

the Array elements

– Method sortsortsortsort takes as its optional argument the name of a function (called the comparatorfunction) that compares its two arguments and returns a negative value, zero, or a positive

value, if the first argument is less than, equal to, or greater than the second, respectively

• Functions in JavaScript are considered to be data– They can be assigned to variables, stored in ArrayArrayArrayArrays and passed to functions just like other

data

Page 21: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

21

� 2008 Pearson Education,

Inc. All rights reserved.

41

Fig. 10.9 |

Sorting an array

with sortsortsortsort (Part

1 of 2).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.9: Sort.html 10.9: Sort.html 10.9: Sort.html 10.9: Sort.html -------->>>>

6 <!<!<!<!-------- Sorting an array with sort. Sorting an array with sort. Sorting an array with sort. Sorting an array with sort. -------->>>>

7 <html<html<html<html xmlns = xmlns = xmlns = xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Sorting an Array with Array Method sortSorting an Array with Array Method sortSorting an Array with Array Method sortSorting an Array with Array Method sort</title></title></title></title>

10 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

11 <!<!<!<!--------

12 varvarvarvar a = [ a = [ a = [ a = [ 10101010, , , , 1111, , , , 9999, , , , 2222, , , , 8888, , , , 3333, , , , 7777, , , , 4444, , , , 6666, , , , 5555 ];];];];

13

14 document.writeln( document.writeln( document.writeln( document.writeln( "<h1>Sorting an Array</h1>""<h1>Sorting an Array</h1>""<h1>Sorting an Array</h1>""<h1>Sorting an Array</h1>" ););););

15 outputArray( outputArray( outputArray( outputArray( "Data items in original order: ""Data items in original order: ""Data items in original order: ""Data items in original order: ", a ); , a ); , a ); , a );

16 a.sort( compareIntegers ); a.sort( compareIntegers ); a.sort( compareIntegers ); a.sort( compareIntegers ); // sort the array// sort the array// sort the array// sort the array

17 outputArray( outputArray( outputArray( outputArray( "Data items in ascending order: ""Data items in ascending order: ""Data items in ascending order: ""Data items in ascending order: ", a ); , a ); , a ); , a );

18

19 // output the heading followed by the contents of theArray// output the heading followed by the contents of theArray// output the heading followed by the contents of theArray// output the heading followed by the contents of theArray

20 functionfunctionfunctionfunction outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )

21 {{{{

22 document.writeln( document.writeln( document.writeln( document.writeln( "<p>" "<p>" "<p>" "<p>" + heading + + heading + + heading + + heading +

23 theArray.join( theArray.join( theArray.join( theArray.join( " "" "" "" " ) + ) + ) + ) + "</"</"</"</p>"p>"p>"p>" ); ); ); );

24 } // end function outputArray// end function outputArray// end function outputArray// end function outputArray

25

Passes function

compareIntegers to method

a.sort to arrange the elements

of a in ascending numerical

order

� 2008 Pearson Education,

Inc. All rights reserved.

42

Fig. 10.9 |

Sorting an array

with sortsortsortsort (Part

2 of 2).

26 // comparison function for use with sort// comparison function for use with sort// comparison function for use with sort// comparison function for use with sort

27 functionfunctionfunctionfunction compareIntegers( value1, value2 )compareIntegers( value1, value2 )compareIntegers( value1, value2 )compareIntegers( value1, value2 )

28 {{{{

29 returnreturnreturnreturn parseInt( value1 ) parseInt( value1 ) parseInt( value1 ) parseInt( value1 ) ---- parseInt( value2 );parseInt( value2 );parseInt( value2 );parseInt( value2 );

30 }}}} // end function compareIntegers// end function compareIntegers// end function compareIntegers// end function compareIntegers

31 // // // // -------->>>>

32 </script></script></script></script>

33 </head><body></body></head><body></body></head><body></body></head><body></body>

34 </html></html></html></html>

Defines a function

comparing integers

to be passed to

method sort (to

replace the default

string comparison

function)

Page 22: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

22

� 2008 Pearson Education, Inc. All rights reserved.

43

Software Engineering Observation 10.5

Functions in JavaScript are considered to be data. Therefore, functions can be assigned to variables, stored in ArrayArrayArrayArrays and passed to functions just like other data types.

� 2008 Pearson Education, Inc. All rights reserved.

44

10.9 Searching Arrays: Linear Search and

Binary Search

• Linear search algorithm– Iterates through the elements of an array until it finds an element that

matches a search key, and returns the subscript of the element

– If the key is not found, the function returns ----1111

– If the array being searched is not in any particular order, it is just as

likely that the value will be found in the first element as the last

– On average, the program will have to compare the search key with half

the elements of the array

Page 23: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

23

� 2008 Pearson Education,

Inc. All rights reserved.

45

Fig. 10.10 |

Linear search of

an array (Part 1

of 3).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.10: LinearSearch.html 10.10: LinearSearch.html 10.10: LinearSearch.html 10.10: LinearSearch.html -------->>>>

6 <!<!<!<!-------- Linear search of an array. Linear search of an array. Linear search of an array. Linear search of an array. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Linear Search of an ArrayLinear Search of an ArrayLinear Search of an ArrayLinear Search of an Array</title></title></title></title>

10 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

11 <!<!<!<!--------

12 varvarvarvar a = a = a = a = newnewnewnew Array( Array( Array( Array( 100100100100 ); ); ); ); // create an Array// create an Array// create an Array// create an Array

13

14 // fill Array with even integer values from 0 to 198// fill Array with even integer values from 0 to 198// fill Array with even integer values from 0 to 198// fill Array with even integer values from 0 to 198

15 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < a.length; ++i ); i < a.length; ++i ); i < a.length; ++i ); i < a.length; ++i )

16 a[ i ] = a[ i ] = a[ i ] = a[ i ] = 2222 * i;* i;* i;* i;

17

18 // function called when "Search" button is pressed// function called when "Search" button is pressed// function called when "Search" button is pressed// function called when "Search" button is pressed

19 functionfunctionfunctionfunction buttonPressed()buttonPressed()buttonPressed()buttonPressed()

20 {{{{

21 // get the input text field// get the input text field// get the input text field// get the input text field

22 varvarvarvar inputVal = document.getElementById( inputVal = document.getElementById( inputVal = document.getElementById( inputVal = document.getElementById( "inputVal""inputVal""inputVal""inputVal" ););););

23

24 // get the result text field// get the result text field// get the result text field// get the result text field

25 varvarvarvar result = documresult = documresult = documresult = document.getElementById( ent.getElementById( ent.getElementById( ent.getElementById( "result""result""result""result" ););););

26

27 // get the search key from the input text field// get the search key from the input text field// get the search key from the input text field// get the search key from the input text field

28 varvarvarvar searchKey = inputVal.value;searchKey = inputVal.value;searchKey = inputVal.value;searchKey = inputVal.value;

29

Creates a new array to search

Initializes each array element

with a value double its index

� 2008 Pearson Education,

Inc. All rights reserved.

46

Fig. 10.10 |

Linear search of

an array (Part 2

of 3).

30 // Array a is passed to linearSearch even though it// Array a is passed to linearSearch even though it// Array a is passed to linearSearch even though it// Array a is passed to linearSearch even though it

31 // is a global variable. Normally an array will// is a global variable. Normally an array will// is a global variable. Normally an array will// is a global variable. Normally an array will

32 // be passed to a method for searching.// be passed to a method for searching.// be passed to a method for searching.// be passed to a method for searching.

33 varvarvarvar element = linearSearch( a, parseInt( searchKeelement = linearSearch( a, parseInt( searchKeelement = linearSearch( a, parseInt( searchKeelement = linearSearch( a, parseInt( searchKey ) );y ) );y ) );y ) );

34

35 ifififif ( element != ( element != ( element != ( element != ----1111 ))))

36 result.value =result.value =result.value =result.value = "Found value in element ""Found value in element ""Found value in element ""Found value in element " + element;+ element;+ element;+ element;

37 elseelseelseelse

38 result.value = result.value = result.value = result.value = "Value not found""Value not found""Value not found""Value not found";;;;

39 } } } } // end function buttonPressed// end function buttonPressed// end function buttonPressed// end function buttonPressed

40

41 // Search "theArray" for the specified "key" value// Search "theArray" for the specified "key" value// Search "theArray" for the specified "key" value// Search "theArray" for the specified "key" value

42 functionfunctionfunctionfunction linearSearch( theArray, key ) linearSearch( theArray, key ) linearSearch( theArray, key ) linearSearch( theArray, key )

43 { { { {

44 // iterates through each element of the array in order // iterates through each element of the array in order // iterates through each element of the array in order // iterates through each element of the array in order

45 forforforfor ( ( ( ( varvarvarvar n = n = n = n = 0000; n < theArray.; n < theArray.; n < theArray.; n < theArray.length; ++n )length; ++n )length; ++n )length; ++n )

46 ifififif ( theArray[ n ] == key )( theArray[ n ] == key )( theArray[ n ] == key )( theArray[ n ] == key )

47 returnreturnreturnreturn n;n;n;n;

48

49 returnreturnreturnreturn ----1111;;;;

50 } } } } // end function linearSearch// end function linearSearch// end function linearSearch// end function linearSearch

51 // // // // -------->>>>

52 </scri</scri</scri</script>pt>pt>pt>

53 </head></head></head></head>

54

Calls function linearSearch on

array a with the value input by the user

Iterates through every element of

the array until the key is found

If the key is encountered, the

index of the element with the

key as its value is returned

If the key is not found, -1 is

returned

Page 24: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

24

� 2008 Pearson Education,

Inc. All rights reserved.

47

Fig. 10.10 |

Linear search of

an array (Part 3

of 3).

55 <body><body><body><body>

56 <form action = <form action = <form action = <form action = """""""">>>>

57 <p><p><p><p>Enter integer search keyEnter integer search keyEnter integer search keyEnter integer search key<br /><br /><br /><br />

58 <input id =<input id =<input id =<input id = "inputVal""inputVal""inputVal""inputVal" type =type =type =type = "text""text""text""text" />/>/>/>

59 <input type =<input type =<input type =<input type = "button""button""button""button" value =value =value =value = "Search""Search""Search""Search"

60 onclick =onclick =onclick =onclick = "buttonPressed()""buttonPressed()""buttonPressed()""buttonPressed()" /><br/><br/><br/><br /></p>/></p>/></p>/></p>

61 <p><p><p><p>ResultResultResultResult<br /><br /><br /><br />

62 <input id =<input id =<input id =<input id = "result""result""result""result" type =type =type =type = "text""text""text""text" size =size =size =size = "30""30""30""30" /></p>/></p>/></p>/></p>

63 </form></form></form></form>

64 </body></body></body></body>

65 </html></html></html></html>

When the Search button is

pressed, calls function

buttonPressed

� 2008 Pearson Education, Inc. All rights reserved.

48

10.9 Searching Arrays: Linear Search and

Binary Search (Cont.)

• Binary search algorithm– More efficient than the linear search algorithm

– Requires that the array be sorted

– Tests the middle element in the array and returns the index if it matches the search key

– If not, it cuts the list in half, depending on whether the key is greater than or less than themiddle element, and repeats the process on the remaining half of the sorted list

– The algorithm ends by either finding an element that matches the search key or reducing thesubarray to zero size

• Tremendous increase in performance over the linear search– For a one-billion-element array, this is the difference between an average of 500 million

comparisons and a maximum of 30 comparisons

• The maximum number of comparisons needed for the binary searchof any sorted array is the exponent of the first power of 2 greater thanthe number of elements in the array

Page 25: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

25

� 2008 Pearson Education,

Inc. All rights reserved.

49

Fig. 10.11 |

Binary search of

an array (Part 1

of 5).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC " " " "----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig. Fig. Fig. Fig. 10.11: BinarySearch.html 10.11: BinarySearch.html 10.11: BinarySearch.html 10.11: BinarySearch.html -------->>>>

6 <!<!<!<!-------- Binary search of an array. Binary search of an array. Binary search of an array. Binary search of an array. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head> <head> <head> <head>

9 <title><title><title><title>Binary SearchBinary SearchBinary SearchBinary Search</title></title></title></title>

10 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

11 <!<!<!<!--------

12 varvarvarvar a = a = a = a = newnewnewnew Array( Array( Array( Array( 15151515 ); ); ); );

13

14 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < a.length; ; i < a.length; ; i < a.length; ; i < a.length; ++i )++i )++i )++i )

15 a[ i ] = a[ i ] = a[ i ] = a[ i ] = 2222 * i; * i; * i; * i;

16

17 // function called when "Search" button is pressed // function called when "Search" button is pressed // function called when "Search" button is pressed // function called when "Search" button is pressed

18 functionfunctionfunctionfunction buttonPressed() buttonPressed() buttonPressed() buttonPressed()

19 { { { {

20 varvarvarvar inputVal = document.getElementById( inputVal = document.getElementById( inputVal = document.getElementById( inputVal = document.getElementById( "inputVal""inputVal""inputVal""inputVal" ); ); ); );

21 varvarvarvar result = document.getElementById( result = document.getElementById( result = document.getElementById( result = document.getElementById( "result""result""result""result" ); ); ); );

22 varvarvarvar searchKey = inputVal.value; searchKey = inputVal.value; searchKey = inputVal.value; searchKey = inputVal.value;

23

24 result.value = result.value = result.value = result.value = "Portions of array searched"Portions of array searched"Portions of array searched"Portions of array searched\\\\n"n"n"n";;;;

25

� 2008 Pearson Education,

Inc. All rights reserved.

50

Fig. 10.11 |

Binary search of

an array (Part 2

of 5).

26 // Array a is passed to binarySearch even though it// Array a is passed to binarySearch even though it// Array a is passed to binarySearch even though it// Array a is passed to binarySearch even though it

27 // is a global variable. This is done because // is a global variable. This is done because // is a global variable. This is done because // is a global variable. This is done because

28 // normally an array is passed to a method// normally an array is passed to a method// normally an array is passed to a method// normally an array is passed to a method

29 // for searching.// for searching.// for searching.// for searching.

30 varvarvarvar element element element element ====

31 binarySearch( a, parseInt( searchKey ) );binarySearch( a, parseInt( searchKey ) );binarySearch( a, parseInt( searchKey ) );binarySearch( a, parseInt( searchKey ) );

32

33 ifififif ( element != ( element != ( element != ( element != ----1111 ))))

34 result.value += result.value += result.value += result.value += """"\\\\nFound value in element "nFound value in element "nFound value in element "nFound value in element " + element;+ element;+ element;+ element;

35 elseelseelseelse

36 result.value +=result.value +=result.value +=result.value += """"\\\\nValue not found"nValue not found"nValue not found"nValue not found";;;;

37 } } } } // end function buttonPressed// end function buttonPressed// end function buttonPressed// end function buttonPressed

38

39 // binary search function// binary search function// binary search function// binary search function

40 functionfunctionfunctionfunction binarySearch( theArray, key )binarySearch( theArray, key )binarySearch( theArray, key )binarySearch( theArray, key )

41 {{{{

42 varvarvarvar low = low = low = low = 0000; ; ; ; // low subscript// low subscript// low subscript// low subscript

43 varvarvarvar high = theArray.length high = theArray.length high = theArray.length high = theArray.length ---- 1111; ; ; ; // high subscript// high subscript// high subscript// high subscript

44 varvarvarvar middle; middle; middle; middle; // middle subscript// middle subscript// middle subscript// middle subscript

45

46 whilewhilewhilewhile ( low <= high ) {( low <= high ) {( low <= high ) {( low <= high ) {

47 middle = ( low + high ) / middle = ( low + high ) / middle = ( low + high ) / middle = ( low + high ) / 2222;;;;

48

49 // The following line is used to display the// The following line is used to display the// The following line is used to display the// The following line is used to display the

50 // part of theArray currently being manipulated// part of theArray currently being manipulated// part of theArray currently being manipulated// part of theArray currently being manipulated

51 // during each iteration of // during each iteration of // during each iteration of // during each iteration of the binarythe binarythe binarythe binary

52 // search loop.// search loop.// search loop.// search loop.

53 buildOutput( theArray, low, middle, high );buildOutput( theArray, low, middle, high );buildOutput( theArray, low, middle, high );buildOutput( theArray, low, middle, high );

54

Calls function binarySearch with

arguments a and the key

specified by the user

While the search has not checked

all values, find the midpoint of the

unchecked region

Displays the portion of the array

currently being examined

Page 26: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

26

� 2008 Pearson Education,

Inc. All rights reserved.

51

Fig. 10.11 |

Binary search of

an array (Part 3

of 5).

55 ifififif ( key == theArray[ middle ] ) ( key == theArray[ middle ] ) ( key == theArray[ middle ] ) ( key == theArray[ middle ] ) // match// match// match// match

56 returnreturnreturnreturn middle;middle;middle;middle;

57 elseelseelseelse ifififif ( key < theArray[ middle ] )( key < theArray[ middle ] )( key < theArray[ middle ] )( key < theArray[ middle ] )

58 high = middle high = middle high = middle high = middle ---- 1111; ; ; ; // searc// searc// searc// search low end of arrayh low end of arrayh low end of arrayh low end of array

59 elseelseelseelse

60 low = middle + low = middle + low = middle + low = middle + 1111; ; ; ; // search high end of array// search high end of array// search high end of array// search high end of array

61 } } } } // end while// end while// end while// end while

62

63 returnreturnreturnreturn ----1111; ; ; ; // searchKey not found// searchKey not found// searchKey not found// searchKey not found

64 } } } } // end function binarySearch// end function binarySearch// end function binarySearch// end function binarySearch

65

66 // Build one row of output showing the current// Build one row of output showing the current// Build one row of output showing the current// Build one row of output showing the current

67 // part of the array being processed.// part of the array being processed.// part of the array being processed.// part of the array being processed.

68 functionfunctionfunctionfunction buildOutput( theArray, low, mid, high )buildOutput( theArray, low, mid, high )buildOutput( theArray, low, mid, high )buildOutput( theArray, low, mid, high )

69 {{{{

70 varvarvarvar result = document.getElementById( result = document.getElementById( result = document.getElementById( result = document.getElementById( "result""result""result""result" ););););

71

72 forforforfor ( ( ( ( varvarvarvar i = i = i = i = 0000; i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ ); i < theArray.length; i++ )

73 {{{{

74 ifififif ( i < low || i > high )( i < low || i > high )( i < low || i > high )( i < low || i > high )

75 result.value += result.value += result.value += result.value += " "" "" "" ";;;;

76 elseelseelseelse ifififif ( ( ( ( i == mid ) i == mid ) i == mid ) i == mid ) // mark middle element in output// mark middle element in output// mark middle element in output// mark middle element in output

77 result.value += theArray[ i ] + result.value += theArray[ i ] + result.value += theArray[ i ] + result.value += theArray[ i ] +

78 ( theArray[ i ] < ( theArray[ i ] < ( theArray[ i ] < ( theArray[ i ] < 10101010 ? ? ? ? "* ""* ""* ""* " : : : : "* ""* ""* ""* " ););););

79 elseelseelseelse

80 rrrresult.value += theArray[ i ] + esult.value += theArray[ i ] + esult.value += theArray[ i ] + esult.value += theArray[ i ] +

81 ( theArray[ i ] < ( theArray[ i ] < ( theArray[ i ] < ( theArray[ i ] < 10101010 ???? " " " " " " " " : : : : " " " " " " " " ););););

82 } } } } // end for// end for// end for// end for

83

If the middle element’s value is

the key, return its subscript

Otherwise, if the middle

element’s value is higher than

the key, we only need to search

the bottom half of the array

Otherwise, if the middle

element’s value is lower than the

key, we only need to search the

higher half of the array

If we’ve covered the whole array

without encountering the key,

return -1

� 2008 Pearson Education,

Inc. All rights reserved.

52

Fig. 10.11 |

Binary search of

an array (Part 4

of 5).

84 result.value += result.value += result.value += result.value += " " " "\\\\n"n"n"n";;;;

85 } } } } // end function buildOutput// end function buildOutput// end function buildOutput// end function buildOutput

86 // // // // -------->>>>

87 </script> </script> </script> </script>

88 </head> </head> </head> </head>

89

90 <body> <body> <body> <body>

91 <form action = <form action = <form action = <form action = """""""">>>>

92 <p> <p> <p> <p>Enter integer search keyEnter integer search keyEnter integer search keyEnter integer search key<br /><br /><br /><br />

93 <input id = <input id = <input id = <input id = "inputVal""inputVal""inputVal""inputVal" type = type = type = type = "text" "text" "text" "text" />/>/>/>

94 <input type = <input type = <input type = <input type = "button""button""button""button" value = value = value = value = "Search""Search""Search""Search"

95 onclick = onclick = onclick = onclick = "buttonPressed()""buttonPressed()""buttonPressed()""buttonPressed()" /><br /></p> /><br /></p> /><br /></p> /><br /></p>

96 <p><p><p><p>ResultResultResultResult<br /><br /><br /><br />

97 <textarea id = <textarea id = <textarea id = <textarea id = "result""result""result""result" rows = rows = rows = rows = "7""7""7""7" cols = cols = cols = cols = "60""60""60""60">>>>

98 </textarea></p> </textarea></p> </textarea></p> </textarea></p>

99 </form> </form> </form> </form>

100 </body> </body> </body> </body>

101 </html></html></html></html>

Page 27: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

27

� 2008 Pearson Education, Inc. All rights reserved.

53

Fig. 10.11 | Binary search of an array (Part 5 of 5).

� 2008 Pearson Education, Inc. All rights reserved.

54

10.10 Multidimensional Arrays

• To identify a particular two-dimensional multidimensional array element– Specify the two subscripts

– By convention, the first identifies the element’s row, and the second identifies the element’s column

• In general, an array with m rows and n columns is called an m-by-n array

• Two-dimensional array element accessed using an element name of the form a[ i ][ ja[ i ][ ja[ i ][ ja[ i ][ j ]]]]– aaaa is the name of the array

– iiii and jjjj are the subscripts that uniquely identify the row and column

• Multidimensional arrays are maintained as arrays of arrays

Page 28: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

28

� 2008 Pearson Education, Inc. All rights reserved.

55

Fig. 10.12 | Two-dimensional array with three rows and four columns.

� 2008 Pearson Education, Inc. All rights reserved.

56

10.10 Multidimensional Arrays (Cont.)

• Multidimensional arrays can be initialized in declarations like a one-dimensional array, with values grouped by row in square brackets– The interpreter determines the number of rows by counting the number of sub initializer

– The interpreter determines the number of columns in each row by counting the number of values in the sub-array that initializes the row

• The rows of a two-dimensional array can vary in length

• A multidimensional array in which each row has a different number of columns can be allocated dynamically with operator newnewnewnew

Page 29: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

29

� 2008 Pearson Education,

Inc. All rights reserved.

57

Fig. 10.13 |

Initializing

multidimensional

arrays (Part 1 of

2).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.13: InitArray3.html 10.13: InitArray3.html 10.13: InitArray3.html 10.13: InitArray3.html -------->>>>

6 <!<!<!<!-------- Initializing multidimensional arraInitializing multidimensional arraInitializing multidimensional arraInitializing multidimensional arrays. ys. ys. ys. -------->>>>

7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Initializing Multidimensional ArraysInitializing Multidimensional ArraysInitializing Multidimensional ArraysInitializing Multidimensional Arrays</title></title></title></title>

10 <script type = <script type = <script type = <script type = "text/javascript""text/javascript""text/javascript""text/javascript">>>>

11 <!<!<!<!--------

12 varvarvarvar array1 = [ [ array1 = [ [ array1 = [ [ array1 = [ [ 1111, , , , 2222, , , , 3333 ], ], ], ], // first row// first row// first row// first row

13 [ [ [ [ 4444, , , , 5555, , , , 6666 ] ]; ] ]; ] ]; ] ]; // second row// second row// second row// second row

14 varvarvarvar array2 = [ [ array2 = [ [ array2 = [ [ array2 = [ [ 1111, , , , 2222 ], ], ], ], // first row// first row// first row// first row

15 [ [ [ [ 3333 ], ], ], ], // second row// second row// second row// second row

16 [ [ [ [ 4444, , , , 5555, , , , 6666 ] ]; ] ]; ] ]; ] ]; // third row// third row// third row// third row

17

18 outpoutpoutpoutputArray( utArray( utArray( utArray( "Values in array1 by row""Values in array1 by row""Values in array1 by row""Values in array1 by row", array1 );, array1 );, array1 );, array1 );

19 outputArray( outputArray( outputArray( outputArray( "Values in array2 by row""Values in array2 by row""Values in array2 by row""Values in array2 by row", array2 );, array2 );, array2 );, array2 );

20

21 functionfunctionfunctionfunction outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )outputArray( heading, theArray )

22 {{{{

23 document.writeln( document.writeln( document.writeln( document.writeln( "<h2>" "<h2>" "<h2>" "<h2>" + heading + + heading + + heading + + heading + "</h2><pre>"</h2><pre>"</h2><pre>"</h2><pre>"""" ););););

24

25 // iterates through the set of one// iterates through the set of one// iterates through the set of one// iterates through the set of one----dimensional arraysdimensional arraysdimensional arraysdimensional arrays

26 forforforfor ( ( ( ( varvarvarvar i i i i inininin theArray )theArray )theArray )theArray )

27 { { { {

28 // iterates t// iterates t// iterates t// iterates through the elements of each onehrough the elements of each onehrough the elements of each onehrough the elements of each one----dimensional dimensional dimensional dimensional

29 // array// array// array// array

30 forforforfor ( ( ( ( varvarvarvar j j j j inininin theArray[ i ] )theArray[ i ] )theArray[ i ] )theArray[ i ] )

31 document.write( theArray[ i ][ j ] + document.write( theArray[ i ][ j ] + document.write( theArray[ i ][ j ] + document.write( theArray[ i ][ j ] + " " " " " " " " ););););

Initializes array1 with an

initializer list of sub initializer lists

Initializes array2 with rows of

different lengths

Nested for…in statements

traverse the arrays by iterating

through the sets of one-dimensional

arrays, then through the elements of

each of those one-dimensional

arrays

� 2008 Pearson Education,

Inc. All rights reserved.

58

Fig. 10.13 |

Initializing

multidimensional

arrays (Part 2 of

2).

32

33 document.writeln( document.writeln( document.writeln( document.writeln( "<br />""<br />""<br />""<br />" ); ); ); );

34 } } } } // end for// end for// end for// end for

35

36 document.writeln( document.writeln( document.writeln( document.writeln( "</pre>" "</pre>" "</pre>" "</pre>" ););););

37 } } } } // end function outputArray// end function outputArray// end function outputArray// end function outputArray

38 // // // // -------->>>>

39 </script> </script> </script> </script>

40 </head><body></body> </head><body></body> </head><body></body> </head><body></body>

41 </html></html></html></html>

Page 30: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

30

� 2008 Pearson Education, Inc. All rights reserved.

59

10.11 Building an Online Quiz

• XHTML formformformform elements can be accessed individually using getElementByIdgetElementByIdgetElementByIdgetElementById or through the elementselementselementselementsproperty of the containing formformformform object

•elementselementselementselements property – contains an array of all the formformformform’s controls

• Property checkedcheckedcheckedchecked of a radio button – truetruetruetruewhen the radio button is selected

– falsefalsefalsefalsewhen the radio button is not selected

� 2008 Pearson Education,

Inc. All rights reserved.

60

Fig. 10.14 |

Online quiz

graded with

JavaScript

(Part 1 of 3).

1 <?xml version = <?xml version = <?xml version = <?xml version = "1.0" "1.0" "1.0" "1.0" encoding = encoding = encoding = encoding = "utf"utf"utf"utf----8"8"8"8"?>?>?>?>

2 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>

4

5 <!<!<!<!-------- Fig.Fig.Fig.Fig. 10.14: quiz.html 10.14: quiz.html 10.14: quiz.html 10.14: quiz.html -------->>>>

6 <!<!<!<!-------- Online quiz graded with JavaScript. Online quiz graded with JavaScript. Online quiz graded with JavaScript. Online quiz graded with JavaScript. -------->>>>

7 <html xmlns =<html xmlns =<html xmlns =<html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>

8 <head><head><head><head>

9 <title><title><title><title>Online QuizOnline QuizOnline QuizOnline Quiz</title></title></title></title>

10 <script type = <script type = <script type = <script type = "text/JavaScript""text/JavaScript""text/JavaScript""text/JavaScript">>>>

11 <!<!<!<!--------

12 functionfunctionfunctionfunction checkAnswers()checkAnswers()checkAnswers()checkAnswers()

13 {{{{

14 varvarvarvar myQuiz = documenmyQuiz = documenmyQuiz = documenmyQuiz = document.getElementById( t.getElementById( t.getElementById( t.getElementById( "myQuiz""myQuiz""myQuiz""myQuiz" ););););

15

16 // determine whether the answer is correct// determine whether the answer is correct// determine whether the answer is correct// determine whether the answer is correct

17 ifififif ( myQuiz.elements[ ( myQuiz.elements[ ( myQuiz.elements[ ( myQuiz.elements[ 1111 ].checked )].checked )].checked )].checked )

18 alert( alert( alert( alert( "Congratulations, your answer is correct""Congratulations, your answer is correct""Congratulations, your answer is correct""Congratulations, your answer is correct" ););););

19 elseelseelseelse // if the ans// if the ans// if the ans// if the answer is incorrectwer is incorrectwer is incorrectwer is incorrect

20 alert( alert( alert( alert( "Your answer is incorrect. Please try again""Your answer is incorrect. Please try again""Your answer is incorrect. Please try again""Your answer is incorrect. Please try again" ););););

21 } } } } // end function checkAnswers// end function checkAnswers// end function checkAnswers// end function checkAnswers

22 -------->>>>

23 </script></script></script></script>

24 </head></head></head></head>

25 <body><body><body><body>

26 <form id = <form id = <form id = <form id = "myQuiz""myQuiz""myQuiz""myQuiz" onsubmit = onsubmit = onsubmit = onsubmit = "checkA"checkA"checkA"checkAnswers()"nswers()"nswers()"nswers()" action = action = action = action = """""""">>>>

27 <p><p><p><p>Select the name of the tip that goes with the Select the name of the tip that goes with the Select the name of the tip that goes with the Select the name of the tip that goes with the

28 image shown:image shown:image shown:image shown:<br /><br /><br /><br />

29 <img src=<img src=<img src=<img src="EPT.gif""EPT.gif""EPT.gif""EPT.gif" alt=alt=alt=alt="mystery tip""mystery tip""mystery tip""mystery tip"/>/>/>/>

30 <br /><br /><br /><br />

Checks to see if the second radio button

of the myQuiz form is selected

Page 31: 10-Lect10-JavaScropt-Arraysparamesh/COMP0011/10-Handout-Lect10...10.3 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new

31

� 2008 Pearson Education,

Inc. All rights reserved.

61

Fig. 10.14 |

Online quiz

graded with

JavaScript

(Part 2 of 3).

31

32 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "radiobutton" "radiobutton" "radiobutton" "radiobutton" value = value = value = value = "CPE""CPE""CPE""CPE" />/>/>/>

33 <label><label><label><label>Common Programming ErrorCommon Programming ErrorCommon Programming ErrorCommon Programming Error</label></label></label></label>

34

35 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "radiobutton""radiobutton""radiobutton""radiobutton" value = value = value = value = "EPT""EPT""EPT""EPT" />/>/>/>

36 <label><label><label><label>ErrorErrorErrorError----PrevPrevPrevPrevention Tipention Tipention Tipention Tip</label></label></label></label>

37

38 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "radiobutton" "radiobutton" "radiobutton" "radiobutton" value = value = value = value = "PERF""PERF""PERF""PERF" />/>/>/>

39 <label><label><label><label>Performance TipPerformance TipPerformance TipPerformance Tip</label></label></label></label>

40

41 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "radiobutton" "radiobutton" "radiobutton" "radiobutton" value = value = value = value = "PORT""PORT""PORT""PORT" />/>/>/>

42 <lab<lab<lab<label>el>el>el>Portability TipPortability TipPortability TipPortability Tip</label><br /></label><br /></label><br /></label><br />

43

44 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" name = name = name = name = "submit""submit""submit""submit" value = value = value = value = "Submit""Submit""Submit""Submit" />/>/>/>

45 <input type = <input type = <input type = <input type = "reset""reset""reset""reset" name = name = name = name = "reset""reset""reset""reset" value = value = value = value = "Reset""Reset""Reset""Reset" />/>/>/>

46 </p></p></p></p>

47 </form></form></form></form>

48 </body></body></body></body>

49 </html></html></html></html>

myQuiz.elements[0]

myQuiz.elements[1]

myQuiz.elements[2]

myQuiz.elements[3]

� 2008 Pearson Education, Inc. All rights reserved.

62

Fig. 10.14 | Online quiz graded with JavaScript

(Part 3 of 3).