Java Reference
In-Depth Information
Length of an Array
Every
Array
object has a property named
length
that is maintained automatically when
elements are added and removed from the array. The
length
property makes an array
different from other types of objects. For a dense array,
length
is one more than the
largest index in the array. For a sparse array, it is guaranteed to be greater than the largest
index of all elements (existing and missing).
The
length
property of an array is writable. That is, you can also change it in code. If
you set
length
to a value greater than the current value,
length
is changed to the new value,
creating a sparse array towards the end. If you set
length
to a value less than its current value,
all elements from the end are deleted until a nondeletable element is found that is greater
than or equal to the new
length
value. That is, setting
length
to a smaller value make the
array shrink up to a nondeletable element. The following examples will make this rule clear:
var names = new Array("Fu", "Li", "Do", "Ho");
print("names.length = " + names.length + ", Elements = " + names);
print("Setting length to 10...");
names.length = 10;
print("names.length = " + names.length + ", Elements = " + names);
print("Setting length to 0...");
names.length = 0;
print("names.length = " + names.length + ", Elements = " + names);
print("Recreating the array...");
names = new Array("Fu", "Li", "Do", "Ho");
print("names.length = " + names.length + ", Elements = " + names);
print('Making "Do" non-configurable...');
// Makes "Do" non-configurable (non-deletable)
Object.defineProperty(names, "2", {configurable:false});
print("Setting length to 0...");
names.length = 0; // Will delete only "Ho" as "Do" is non-deletable
print("names.length = " + names.length + ", Elements = " + names);
names.length = 4, Elements = Fu,Li,Do,Ho
Setting length to 10...
names.length = 10, Elements = Fu,Li,Do,Ho,,,,,,
Setting length to 0...
names.length = 0, Elements =
Recreating the array...
names.length = 4, Elements = Fu,Li,Do,Ho
Making "Do" non-configurable...
Setting length to 0...
names.length = 3, Elements = Fu,Li,Do
Search WWH ::
Custom Search