Javascript Arrays
An Array is an object which
stores multiple values and has
various properties. When you
declare an array, you must declare
the name of it, and then how many
values it will need to store. It
is important to realize that each
value is stored in one of the
elements of the array, and these
elements start at 0. This means
that the first value in the array
is really in the 0 element, and
the second number is really in the
first element. So for example, if
I want to store 10 values in my
array, the storage elements would
range from 0-9.
The notation for declaring an
array looks like this:
myArray = new Array(10); foo =
new Array(5);
Initially, all values are set
to null. The notation for
assigning values to each unit
within the array looks like this:
myArray[0] = 56;
myArray[1] = 23;
myArray[9] = 44;
By putting the element number in
brackets [ ] after the array's
name, you can assign a value to
that specific element. Note that
there is no such element, in this
example, as myArray[10]. Remember,
the elements begin at myArray[0]
and go up to myArray[9].
In JavaScript, however, an
array's length increases if you
assign a value to an element
higher than the current length of
the array. The following code
creates an array of length zero,
then assigns a value to element
99. This changes the length of the
array to 100.
colors = new Array();
colors[99] = "midnightblue";
Be careful to reference the
right cells, and make sure to
reference them properly!
Because arrays are objects,
they have certain properties that
are pre-defined for your
convenience. For example, you can
find out how many elements myArray
has and store this value in a
variable called numberOfElements
by using:
numberOfElements = myArray.length;
|