var a = new Array( ); // a.length == 0 (no elements defined)
a = new Array(10); // a.length == 10 (empty elements 0-9 defined)
a = new Array(1,2,3); // a.length == 3 (elements 0-2 defined)
a = [4, 5]; // a.length == 2 (elements 0 and 1 defined)
a[5] = -1; // a.length == 6 (elements 0, 1, and 5 defined)
a[49] = 0; // a.length == 50 (elements 0, 1, 5, and 49 defined)
Remember that array indexes must be less than
232 -1, which means that the largest
possible value for the length property is
232 -1.
Probably the most common use of the length
property of an array is to allow us to loop through the elements of
an array:
var fruits = ["mango", "banana", "cherry", "pear"];
for(var i = 0; i < fruits.length; i++)
alert(fruits[i]);
This example assumes, of course, that elements of the array are
contiguous and begin at element 0. If this were not the case, we
would want to test that each array element was defined before using
it:
for(var i = 0; i < fruits.length; i++)
if (fruits[i] != undefined) alert(fruits[i]);