Arrays come in all shapes and sizes but they all have one thing in common, they store a collection of values. Each value within an array is referenced by an index number.
Arrays are indexed by enclosing the index number within square brackets after the array name.
As Javascript counts from zero the array indexes begin with zero, so myArray[0] refers to the first element of the array.
Arrays can contain any type of data and reference other arrays, objects, or functions.
|
<script type="text/javascript"> |
Arrays can be written in more than one way.
Dense array
arrayName = new Array("a","b","c","d")
Referenced as arrayName[0] would give a
Conventional array
arrayName = new Array()
arrayName[0] = "a"
arrayName[1] = "b"
arrayName[2] = "c"
arrayName[3] = "d"
Referenced as arrayName[1] would give b
Literal Notation
arrayName=["a","b","c","d"]
Referenced as arrayName[3] would give d
Multi-dimensional arrays
arrayName=new Array()
arrayName[0]=new Array(1,2,3,4)
arrayName[1]=new Array("A","B","C","D")
| Referenced as | arrayName[0][3] would give 4 arrayName[1][3] would give D |
arrayName=new Array()
arrayName["0,0"]="0"
arrayName["0,1"]="1"
arrayName["0,2"]="2"
arrayName["0,3"]="3"
arrayName["1,0"]="A"
arrayName["1,1"]="B"
arrayName["1,2"]="C"
arrayName["1,3"]="D"
| Referenced as | arrayName[0+","+0] would give 0 arrayName[1+","+0] would give A |
arrayName=new Array( ['0 0','0 1'] , ['1 0','1 1'] , ['2 0','2 1','2 2'] , ['3 0','3 1','3 4','3 3'] )
Or
arrayName=new Array()
arrayName[0] = ['0 0','0 1']
arrayName[1] = ['1 0','1 1']
arrayName[2] = ['2 0','2 1','2 2']
arrayName[3] = ['3 0','3 1','3 4','3 3']
Referenced as arrayName[n][n]
In the above examples all the arrays have numerically ordered indexes. If you wanted to add or delete an index, or just reorganise your data, you would then have to re-number the indexes to ensure a numerical order remained.
With the following example the array.length property is used instead of a number, this allows you to add, delete indexes, or rearrange the order of your array without the need to re-number the arrays indexes.
arrayName=new Array()
arrayName[arrayName.length]="A"
arrayName[arrayName.length]="B"
arrayName[arrayName.length]="C"
arrayName[arrayName.length]="D"
arrayName[arrayName.length]="E"
<script type="text/javascript">
<!--
myArray0=["a"]
myArray1=["Hello","World"]
myArray2=["1","2","3"]
myArray3=["Once","upon","a","time"]
myArray4=["Jan","Feb","March","April","May"]
function showMe2(){
count=0
while(window["myArray"+count]){
document.getElementById("display").innerHTML+=" myArray"+count+" = "
array_length=window['myArray' + count].length
for(var i=0;i<array_length;i++){
document.getElementById("display").innerHTML+=window['myArray' + count][i]+" "
}
document.getElementById("display").innerHTML+="<P>"
count++
}
}
setTimeout("showMe2()",100)
// -->
</script>
<div id="display"></div>