The length property of an array indicates one more than the maximum numeric index value that has currently been used. This is because Array elements start indexing from zero rather than one.
Note that this is not necessarily a count of the exact number of elements in the array just an indication of its range of index values.
Whenever a property is added whose name is an array index, the length property is recomputed to allow the length of the array to contain the new element that was added.
Furthermore, when the length value is set explicitly, it may truncate the array and any properties whose name is a numeric value that falls outside the bounds indicated by the length value will be deleted.
This does only affect properties that belong to an Array object itself though. Any properties that are inherited from a parent or prototype are unaffected.
The maximum value for an Array length is 4,294,967,295. This is because a 32 bit integer is used to index the array. Arrays of this length are unlikely to be encountered often! A web page containing an array of that size could take several weeks to download, that is assuming you had 4 GBytes of memory available and that your web browser could address that much storage.
Although this property is marked as ReadOnly, there are some sub-classes of the Array object that allow you to modify the length property directly.
The length property is so unreliable as to be virtually unusable unless you strictly constrain the way you add elements to the array. If you add elements to an array using associative names, the length property is not changed at all and will return a zero value.
If you then add an element to the array whose index is a numeric value, then the length property will be set to a value that is one more than the highest numbered numerically indexed item in the array. This following fragment of code yields an array length property value of 3:
var myArray = new Array(); myArray[2] = "ABC"; myArray["zero"] = "ABC"; myArray["one"] = "one"; myArray["two"] = "two"; myArray[0] = "ABC";
This behavior is correct according to the ECMA specification but it is not a genuine measurement of the array length, merely an indication of the highest numerically indexed Array element. It should be used for controlling enumeration loops but not for measuring array element item counts.
WebTV platforms can only address array indices using a 16 bit value and can only access 32768 items in an array.
ECMA 262 edition 2 - section - 15.4.2
ECMA 262 edition 2 - section - 15.4.3.2
ECMA 262 edition 2 - section - 15.4.5.2
ECMA 262 edition 3 - section - 15.4.5.2
Wrox Instant JavaScript - page - 16
Prev | Home | Next |
Array.join() | Up | Array.pop() |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |