Java Reference
In-Depth Information
As you have already seen, a normal variable can only hold one piece of data at a time. For example, you
can set myVariable to be equal to 25 like so:
myVariable = 25;
and then go and set it to something else, say 35:
myVariable = 35;
However, when you set the variable to 35, the fi rst value of 25 is lost. The variable myVariable now
holds just the number 35.
The following table illustrates the variable:
Va r iable Na me
Va lue
myVariable
35
The difference between such a normal variable and an array is that an array can hold more than one item
of data at the same time. For example, you could use an array with the name myArray to store both the
numbers 25 and 35. Each place where a piece of data can be stored in an array is called an element .
How do you distinguish between these two pieces of data in an array? You give each piece of data an
index value. To refer to that piece of data you enclose its index value in square brackets after the name
of the array. For example, an array called myArray containing the data 25 and 35 could be illustrated
using the following table:
ElementName
Value
myArray[0]
25
myArray[1]
35
Notice that the index values start at 0 and not 1. Why is this? Surely 1 makes more sense — after all, we
humans tend to say the fi rst item of data, followed by the second item, and so on. Unfortunately, com-
puters start from 0, and think of the fi rst item as the zero item, the second as the fi rst item, and so on.
Confusing, but you'll soon get used to this.
Arrays can be very useful since you can store as many (within the limits of the language, which speci-
fi es a maximum of two to the power of 32 elements) or as few items of data in an array as you want.
Also, you don't have to say up front how many pieces of data you want to store in an array, though you
can if you wish.
So how do you create an array? This is slightly different from declaring a normal variable. To create a
new array, you need to declare a variable name and tell JavaScript that you want it to be a new array
using the new keyword and the Array() function. For example, the array myArray could be defi ned
like this:
var myArray = new Array();
Search WWH ::




Custom Search