Java Reference
In-Depth Information
Adding an element to an array is the same as assigning a value at a nonexisting
index. The following code creates an array with three elements and adds the fourth and
fifth elements. Finally, the code prints all elements in the array:
// Create an array with three elements
var names = ["Fu", "Li", "Ho"]
// Add fourth element
names[3] = "Su"; // Adds an element at index 3
// Add fifth element
names[4] = "Bo"; // Adds an element at index 4
// Print all array elements
for(var i = 0, len = names.length; i < len; i++) {
print("names[" + i + "] = " + names[i]);
}
names[0] = Fu
names[1] = Li
names[2] = Ho
names[3] = Su
names[4] = Bo
Recall that an array is an object, so you can add properties to an array just as you add
properties to any other objects. If the property name is not an index, the property will be
simply a property, not an element. A nonelement property does not contribute to length
of the array. The following code creates an array, adds an element and a nonelement
property, and prints the details:
// Create an array with three elements
var names = ["Fu", "Li", "Ho"]
// Add fourth element
names[3] = "Su"; // Adds an element at index 3
// Add a non-element property to the array. The property name is
// "nationality" that is not an index, so it does not define an element.
// Rather, it is a simply property.
names["nationality"] = "Chinese";
print("names.length = " + names.length);
Search WWH ::




Custom Search