Arrays
in JavaScript
Arrays are used to
store numbered pieces of data. Each piece of data is called an element,
and the number assigned to is is called its index.
JavaScript arrays
are very similar to conventional arrays in other programming languages,
but there are some differences:
- An element of an
array can be of any type (character string, integer, Boolean, another
array)
- Different
elements of the same array may be of different types
- The
first element of an array is at index 0
- JS
arrays can be sparse -- i.e. they can contain non-contiguous elements
- JavaScript arrays
are objects so they have properties like length, and built-in methods
like join, reverse and sort
Defining
arrays
- Arrays can be
created like you create objects
- myArray = new
Object()
- myArray[0]
= 1
- myArray[1]
= 2 ...
- You can create
arrays with a constructor
- a
= new EmptyArray(32)
- a
= new Array()
- anotherArray
= new Array(16)
- Define and initialize
arrays at once
- a = new Array(1,
2, 3, "HTML", "MSIE")
Using
array elements
- Reading and
writing
- value = a[0]
- a[1]
= "Dynamic HTML"
- i = 2; a[i]
= "Macromedia Dreamweaver"
- a[i
+ 1] = "Allaire HomeSite 4.5"
- a [10] = a[1]
- myTools[visual]
= "Adobe GoLive"
- myTools[html]
= "Lightning HTML Editor"
- myTools[email]
= "Qualcomm Eudora"
- myTools[graphics]
= "Macromedia Fireworks"
- Adding new elements
- a[0] = 0
- a[1] = 23
- a[1000] = [-1]
- Multi-demensional
arrays - array of arrays
- myTable[state][city]
= "The Big Apple"
JavaScript
Seminar Home | Previous |
Next
Last Modified:
March 2, 2001 UIC Instructional Technology Lab |