Java Reference
In-Depth Information
You can add a property to an array that is a negative number. Notice that a negative
number as a property name does not qualify to be an index, so it will simply add a
property, not an element:
// Create an array with two elements
var names = ["Fu", "Li"]
// Adds property with the name "-1", not an element.
names[-1] = "Do"; // names.length is still 2
print("names.length = " + names.length);
names.length = 2
You can also create a sparse array using an array literal. Using commas without
specifying the elements in the element's list creates a sparse array. Note that in a sparse
array, the index of elements are not contiguous. The following code creates a sparse array:
var names = ["Fu",,"Lo"];
The
names
array contains two elements. They are at index 0 and 2. The element at
index 1 is missing and that is indicated by two consecutive commas. What is the
length
of
the
names
array? It is 3, not 2. Recall that the
length
of an array is always greater than the
maximum index of all elements. The maximum index in the array is 2, so the
length
is 3.
What happens when you try reading
names[1]
, which is a nonexisting element? Reading
names[1]
is simply treated as reading a property named “1” from the
names
object where
the property named “1” does not exist. Recall from
Chapter 4
that reading a non-
existing property of an object returns
undefined
. Therefore,
names[1]
will simply return
undefined
, without causing any errors. If you assign a value to
names[1]
, you are creating
a new element at index 1 and the array will no longer be a sparse array. The following
code shows this rule:
// Create a sparse array with 2 existing and 1 missing elements
var names = ["Fu",,"Lo"]; // names.length is 3
print("names.length = " + names.length);
for(var prop in names) {
print("names[" + prop + "] = " + names[prop]);
}
// Add an element at index 1.
names[1] = "Do"; // names.length is still 3
Search WWH ::
Custom Search