JavaScript: Arrays
Introduction
Arrays
Declaring and Allocating Arrays
Examples Using Arrays
Random Image Generator Using Arrays
References and Reference Parameters
Passing Arrays to Functions
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays
Introduction
Arrays
Data structures of related items
Also called Collections
Dynamic
Arrays
Arrays in JavaScript
Each element referenced by a number
Start at “zeroth element”
Subscript or index
Accessing a specific element
Name of array
Brackets
Number of element
Arrays know their length
length property
Arrays
c[ 0 ] -45
Name of array
c[ 1 ] 6
c[ 2 ] 0
c[ 3 ] 72
c[ 4 ] 1543
c[ 5 ] -89
c[ 6 ] 0
c[ 7 ] 62
c[ 8 ] -3
c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within array c c[ 11 ] 78
Fig. 11.1 A 12-element array.
Arrays
Operators Associativity Type
() [] . left to right highest
++ -- ! right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 11.2 Precedence and associativity of the operators discussed so far.
Declaring and Allocating Arrays
Arrays in memory
Objects
Operator new
Allocates memory for objects
Dynamic memory allocation operator
var c;
c = new Array( 12 );
Examples Using Arrays
Arrays grow dynamically
Allocate more space as items are added
Must initialize array elements
Default value is undefined
for loops convenient
Referring to uninitialized elements or elements
outside array bounds is an error
Examples Using Arrays
Examples Using Arrays
Possible to declare and initialize in one
step
Specify list of values
Initializer list
var n = [ 10, 20, 30, 40, 50 ];
var n = new Array( 10, 20,
30, 40,
50 );
Also possible to only initialize some values
Leave uninitialized elements blank
Uninitialized elements default to “undefined”
Examples Using Arrays
Examples Using Arrays
for…in statement
Perform an action for each element in an array
Iterates over array elements
Assigns each element to specified variable one at a
time
Ignores non-existent elements
Examples Using Arrays
Arrays can provide shorter and cleaner
substitute for switch statements
Each element represents one case
Random Image Generator Using Arrays
Cleaner approach than previous version
Specify any file name rather than integers 1-7
Result of [Link] call is index into array
of image file names
Random Image Generator Using Arrays
References and Reference Parameters
Two ways to pass parameters
Pass-by-value
Pass copy of original value
Default for numbers and booleans
Original variable is unchanged
Pass-by-reference
How objects are passed, like arrays
Pass location in memory of value
Allows direct access to original value
Improves performance
Passing Arrays to Functions
Name of array is argument
Not necessary to also pass size of array
Arrays know their size
Passed by reference
Individual elements are passed by value if numbers
or booleans
[Link]
Creates string containing all array elements
Specify separator
Passing Arrays to Functions
Sorting Arrays
Sorting
Important computing task
[Link]
Defaults to string comparison
Optional comparator function
Return negative if first argument less than second
Return zero if arguments equal
Return positive if first argument greater than second
Sorting an array with sort
Searching Arrays: Linear Search and
Binary Search
Searching
Look for matching key value
Linear search
Iterate through each element until match found
Inefficient
Worst case scenario, must test entire array
Binary search
Requires sorted data
Cuts search range in half each iteration
Efficient
Only look at small fraction of elements
Linear search of an array
Binary search of an array
Multidimensional Arrays
Two-dimensional arrays analogous to
tables
Rows and columns
Specify row first, then column
Two subscripts
Multidimensional Arrays
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ]
[ 3 ]
Row 1
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ]
Row 2 [ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ]
[ 3 ] Column subscript (or index)
Row subscript (or index)
Array name
Fig. 11.12 Two-dimensional array with three rows and four columns.
Multidimensional Arrays
Declaring and initializing multidimensional
arrays
Group by row in square brackets
Treated as arrays of arrays
Creating array b with one row of two elements
and a second row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
Multidimensional Arrays
Also possible to use new operator
Create array b with two rows, first with five
columns and second with three:
var b;
b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );
Initializing multidimensional arrays
Different array manipulations using for
and for/in
var total = 0;
for (var row = 0; row < [Link]; ++row )
for (var col = 0; col < a[ row ].length; ++col )
total += a[ row ][ col ];
identical to
var total = 0;
for (var row in a )
for (var col in a[ row ] )
total += a[ row ][ col ];
Both statements total the
elements of the array,
one row at a time