JS Arrays
JS Arrays
Objectives
11.1 Introduction
• Arrays
– Data structures of related items
• Also called Collections
– Dynamic
11.2 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
11.2 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
11.2 Arrays
• Arrays in memory
– Objects
– Operator new
• Allocates memory for objects
• Dynamic memory allocation operator
var c;
c = new Array( 12 );
• 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
• Sorting
– Important computing task
• Array.sort
– Defaults to string comparison
– Optional comparator function
• Return negative if first argument less than second
• Return zero if arguments equal
• Return positive if first argument greater than second
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 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Array name
Fig. 11.12 Two-dimensional array with three rows and four columns.
b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );
• Radio buttons
– Represented as an array
• Name of radio buttons is name of array
• One element per button
– checked property is true when selected
• XHTML Forms
– Contain controls, including radio buttons
– action property specifies what happens when submitted
• Can call JavaScript code