HTML and CSS Reference
In-Depth Information
Working with Array Length
A JavaScript array automatically expands in length as more items are added. If you need
to determine the array's current size, you use the property
array
.length
where
array
is the name of the array. The value returned by the
length
property is
equal to one more than the highest index number in the array (because array indices start
at 0 rather than 1). This is not always the same as the number of array values. JavaScript
allows for the creation of
sparse arrays
, in which some array values are left undefined.
For example, the following commands create a sparse array in which only the first and
last items have defined values:
var x = new Array();
x[0] = “Maria”;
x[99] = “80517”;
The value of the
length
property for this array is 100 even though for the moment it only
contains two values. Sparse arrays occur frequently in database applications involving
customer records where items such as mobile phone numbers or postal codes have not
been entered for every person.
Note that you cannot reduce the value of the
length
property without removing items
from the end of your array. For example, the following command would reduce the
monthName
array to the first three months—January, February, and March:
You can add new
items to the end of any
array using the com-
mand
array
[array.
length] =
value;
where
array
is the name
of the array and
value
is the new value to add to
the array.
monthName.length = 3;
There are also JavaScript methods for removing items from the front of an array, which
you'll explore later in this tutorial. Increasing the value of the
length
property adds
more items to an array, but the items have null values until they are defined.
Specifying Array Length
• To determine the size of an array, use the property
array
.length
where
array
is the name of the array.
• To add an item to the end of an array, run the command
array
[
i
] =
value
;
where
i
is an index value higher than the highest index currently in the array. If you
don't know the highest index number, use the property
array
.length
in place of
i
.
• To remove items from an array, run the command
array
.length =
value
;
where
value
is an integer that is smaller than the highest index currently in the array.
In the next section, you'll learn how to use JavaScript methods to reverse and
reorder arrays.