Java Script: Arrays (Chapter 11 in [2])Java Script: Arrays (Chapter 11 in [2])
2
OutlineOutline
IntroductionIntroduction
ArraysArrays
Declaring and Allocating ArraysDeclaring and Allocating Arrays
References and Reference ParametersReferences and Reference Parameters
Passing Arrays to FunctionsPassing Arrays to Functions
Sorting ArraysSorting Arrays
Multidimensional ArraysMultidimensional Arrays
Building an Online QuizBuilding an Online Quiz
Web ResourcesWeb Resources
3
ObjectivesObjectives
In this tutorial, you will learn:In this tutorial, you will learn:
To introduce the array data structure.To introduce the array data structure.
To understand the use of arrays to store, sort andsearch lists and tables of values.To understand the use of arrays to store, sort andsearch lists and tables of values.
To understand how to declare an array, initializean array and refer to individual elements of anarray.To understand how to declare an array, initializean array and refer to individual elements of anarray.
To be able to pass arrays to functions.To be able to pass arrays to functions.
To be able to search and sort an array.To be able to search and sort an array.
To be able to declare and manipulate multi-dimensional arrays.To be able to declare and manipulate multi-dimensional arrays.
4
IntroductionIntroduction
ArraysArrays
Data structures of related itemsData structures of related items
Also called CollectionsAlso called Collections
DynamicDynamic
5
ArraysArrays
Arrays in JavaScriptArrays in JavaScript
Each element referenced by numberEach element referenced by number
Start at zeroth elementStart at zeroth element
Subscript or indexSubscript or index
Accessing specific elementAccessing specific element
Name of arrayName of array
BracketsBrackets
Number of elementNumber of element
Arrays know their lengthArrays know their length
length propertylength property
6
ArraysArrays
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.112-element array.Fig. 11.112-element array.
7
ArraysArrays
8
Declaring and Allocating ArraysDeclaring and Allocating Arrays
Arrays in memoryArrays in memory
ObjectsObjects
Operator newOperator new
Allocates memory for objectsAllocates memory for objects
Dynamic memory allocation operatorDynamic memory allocation operator
var c;new Array( 12 );var c;new Array( 12 );
9
Examples Using ArraysExamples Using Arrays
Arrays grow dynamicallyArrays grow dynamically
Allocate more space as items are addedAllocate more space as items are added
Must initialize array elementsMust initialize array elements
Default value is undefinedDefault value is undefined
for loops convenientfor loops convenient
Referring to uninitialized elements or elementsoutside array bounds is an errorReferring to uninitialized elements or elementsoutside array bounds is an error
Array n1 has five elements.
The for loop initializes the elements in n1 totheir subscript numbers (0 to 4).
Array n2 is an empty array.
The for loop adds five elements to Array n2 andinitialize each element to its subscript number (0 to 4).
Each function displays thecontents of its respective Arrayin an XHTML table.
The first time function ouputArray is called,variable header gets the value of “Array n1contains” and variable theArray gets thevalue of n1.
The second time function ouputArray iscalled, variable header gets the value of“Array n2 contains” and variabletheArray gets the value of n2.
13
Examples Using ArraysExamples Using Arrays
11_03
Fig. 11.3    Initializing the elements of an array.Fig. 11.3    Initializing the elements of an array.
14
Examples Using ArraysExamples Using Arrays
Possible to declare and initialize in one stepPossible to declare and initialize in one step
Specify list of valuesSpecify list of values
Initializer listInitializer list
var 10, 20, 30, 40, 50 ];var new Array( 10, 20, 30, 40, 50 );var 10, 20, 30, 40, 50 ];var new Array( 10, 20, 30, 40, 50 );
Also possible to only initialize some valuesAlso possible to only initialize some values
Leave uninitialized elements blankLeave uninitialized elements blank
Uninitialized elements default to “undefined”Uninitialized elements default to “undefined”
var 10, 20, 40, 50 ];var 10, 20, 40, 50 ];
Array integers1 is initialized using an initializer list.
Two values are not supplied for integers2,which will be displayed as undefined.
17
Examples Using ArraysExamples Using Arrays
Fig. 11.4    Initializing the elements of an array.Fig. 11.4    Initializing the elements of an array.
11_04
18
Examples Using ArraysExamples Using Arrays
forin statementforin statement
Perform an action for each element in an arrayPerform an action for each element in an array
Iterates over array elementsIterates over array elements
Assigns each element to specified variable one at timeAssigns each element to specified variable one at time
Ignores non-existent elementsIgnores non-existent elements
The for loop sums the values contained in the 10-element integer array called theArray.
Variable element is assigned a subscriptin the range of 0 up to, but not including,theArray.length.
21
Examples Using ArraysExamples Using Arrays
Fig. 11.5    Calculating the sum of the elements of an array.Fig. 11.5    Calculating the sum of the elements of an array.
22
Examples Using ArraysExamples Using Arrays
Arrays can provide shorter and cleanersubstitute for switch statementsArrays can provide shorter and cleanersubstitute for switch statements
Each element represents one caseEach element represents one case
RollDie.html(1 of 2)RollDie.html(1 of 2)
Referencing Array frequency replaces the switchstatement used in Chapter 10’s example.
RollDie.html(2 of 2)RollDie.html(2 of 2)
25
Examples Using ArraysExamples Using Arrays
Fig. 11.6    Dice-rolling program using arrays instead of switch.Fig. 11.6    Dice-rolling program using arrays instead of switch.
11_06
26
References and ReferenceParametersReferences and ReferenceParameters
Two ways to pass parametersTwo ways to pass parameters
Pass-by-valuePass-by-value
Pass copy of original valuePass copy of original value
Default for numbers and booleansDefault for numbers and booleans
Original variable is unchangedOriginal variable is unchanged
Pass-by-referencePass-by-reference
How objects are passed, like arraysHow objects are passed, like arrays
Pass location in memory of valuePass location in memory of value
Allows direct access to original valueAllows direct access to original value
Improves performanceImproves performance
27
Passing Arrays to FunctionsPassing Arrays to Functions
Name of array is argumentName of array is argument
Not necessary to also pass size of arrayNot necessary to also pass size of array
Arrays know their sizeArrays know their size
Passed by referencePassed by reference
Individual elements are passed by value if numbers orbooleansIndividual elements are passed by value if numbers orbooleans
Array.joinArray.join
Creates string containing all array elementsCreates string containing all array elements
Specify separatorSpecify separator
The first call to function outputArray displays thecontents of the Array a before it is modified.
Function modifyArray multiplies each element by 2.
Again, function outputArray is called to showthat the contents of Array a have been modified.
Method join takes as its argument a stringcontaining a separator that should be used toseparate the elements of the array in the stringthat is returned.
Function modifyElement multiplies thecontents of a[ 3 ] by 2.
The value of a[ 3 ] is output to show itscontents before it is modified.
Multiply each element in theArray by 2.
31
Passing Arrays to FunctionsPassing Arrays to Functions
Fig. 11.8    Passing arrays and individual array elements to functions.Fig. 11.8    Passing arrays and individual array elements to functions.
11_07
32
Sorting ArraysSorting Arrays
SortingSorting
Important computing taskImportant computing task
Array.sortArray.sort
Defaults to string comparisonDefaults to string comparison
Optional comparator functionOptional comparator function
Return negative if first argument less than secondReturn negative if first argument less than second
Return zero if arguments equalReturn zero if arguments equal
Return positive if first argument greater than secondReturn positive if first argument greater than second
Sort.html(1 of 2)Sort.html(1 of 2)
Method sort takes as its optional argument the name of afunction that compares two arguments and returns a valueof –1, 0 or 1.
Sort.html(2 of 2)Sort.html(2 of 2)
Function compareIntegers calculates the differencebetween the integer values of its arguments.
35
Sorting ArraysSorting Arrays
Fig. 11.9    Sorting an array with sort.Fig. 11.9    Sorting an array with sort.
11_08
36
QuestionQuestion
What is the output if the argument of a.sort()in line #20 is removed.What is the output if the argument of a.sort()in line #20 is removed.
37
Multidimensional ArraysMultidimensional Arrays
Two-dimensional arrays analogous to tablesTwo-dimensional arrays analogous to tables
Rows and columnsRows and columns
Specify row first, then columnSpecify row first, then column
Two subscriptsTwo subscripts
38
Multidimensional ArraysMultidimensional 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.Fig. 11.12   Two-dimensional array with three rows and four columns.
39
Multidimensional ArraysMultidimensional Arrays
Declaring and initializing multidimensionalarraysDeclaring and initializing multidimensionalarrays
Group by row in square bracketsGroup by row in square brackets
Treated as arrays of arraysTreated as arrays of arrays
Creating array b with one row of two elements and asecond row of three elements:Creating array b with one row of two elements and asecond row of three elements:
var 1, ], 3, 4, ];var 1, ], 3, 4, ];
40
Multidimensional ArraysMultidimensional Arrays
Also possible to use new operatorAlso possible to use new operator
Create array b with two rows, first with five columnsand second with three:Create array b with two rows, first with five columnsand second with three:
var b;new Array( );b[ new Array( );b[ new Array( );var b;new Array( );b[ new Array( );b[ new Array( );
Array array1 provides six initializers intwo rows.
Array array2 provides six initializers inthree rows.
Function outputArray displays each array’selements in a Web page.
Referencing the multidimensionalarray theArray.
43
Multidimensional ArraysMultidimensional Arrays
Fig. 11.13    Initializing multidimensional arrays.Fig. 11.13    Initializing multidimensional arrays.
11_11
44
Building an Online QuizBuilding an Online Quiz
Radio buttonsRadio buttons
Represented as an arrayRepresented as an array
Name of radio buttons is name of arrayName of radio buttons is name of array
One element per buttonOne element per button
checked property is true when selectedchecked property is true when selected
XHTML FormsXHTML Forms
Contain controls, including radio buttonsContain controls, including radio buttons
action property specifies what happens whensubmittedaction property specifies what happens whensubmitted
Can call JavaScript codeCan call JavaScript code
Quiz.html(1 of 2)Quiz.html(1 of 2)
Determining the value of propertychecked.
Quiz.html(2 of 2)Quiz.html(2 of 2)
Call the checkAnswers functionwhen the form is submitted.
47
Building an Online QuizBuilding an Online Quiz
Fig. 11.14    Online quiz graded with JavaScript.Fig. 11.14    Online quiz graded with JavaScript.
quiz
quiz2