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
- JS 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
them with a constructor
- a
= new EmptyArray(32)
- a
= new Array()
- anotherArray
= new Array(16)
- Define and initialize
them 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.0"
- a [10] = a[1]
- myTools[visual]
= "GoLive CyberStudio"
- myTools[html]
= "Lightning HTML Editor"
- myTools[email]
= "Qualcomm Eudora"
- myTools[graphics]
= "Adobe Photoshop"
- Multi-demensional
arrays - array of arrays
- myTable[state][city]
= "The big Apple"
JavaScript
Seminar Home | Previous |
Next
Last Modified:
November 2, 1998 Instructional Technology Lab |