↑
Main Page
array
As in strings, the first item in an array is in position 0, the second is in position 1, and so on. To access a
particular item, use square brackets enclosing the position of the item to retrieve. For instance, to output
the string
“green”
from the array defined previously, you do this:
alert(aColors[1]); //outputs “green”
The full size of the array can be determined by using the
length
property. Like the same property in
strings, the length property is always one more than the position of the last item, meaning that an array
with three items has items in positions 0 through 2.
var aColors = new Array(“red”, “green”, “blue”);
alert(aColors.length); //outputs “3”
As mentioned previously, the size of an array can grow and shrink as necessary. So, if you wanted to add
another item to the array defined previously, you can just place the value in the next open position:
var aColors = new Array(“red”, “green”, “blue”);
alert(aColors.length); //outputs “3”
aColors[3] = “purple”;
alert(aColors.length); //outputs “4”
In this code, the next open position is 3, so the value
“purple”
is assigned to it. This addition changes
the length of the array from 3 to 4. But what would happen if you placed a value in position 25 of this
array? ECMAScript fills in all positions from 3 to 24 with the value
null
; then it places the appropriate
value in position 25, increasing the size of the array to 26:
var aColors = new Array(“red”, “green”, “blue”);
alert(aColors.length); //outputs “3”
aColors[25] = “purple”;
aColors(arr.length); //outputs “26”
You can also define an
Array
object by using the literal representation, which is indicated by using
square brackets ([ and ]) and separating the values with commas. For instance, the previous example can
be rewritten in the following form:
var aColors = [“red”, “green”, “blue”];
alert(aColors.length); //outputs “3”
aColors[25] = “purple”;
alert(aColors.length); //outputs “26”
Note that, in this case, the
Array
class is never mentioned explicitly. The square brackets imply that the
enclosed values are to be made into an
Array
object. Arrays declared in this way are exactly equal to
arrays declared in the more traditional manner.
Arrays can contain a maximum of 4294967295 items, which should be plenty for
almost all programming needs. If you try to add more than that number, an excep-
tion occurs.
71
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 71
Free JavaScript Editor
Ajax Editor
©
→ R7