Java Reference
In-Depth Information
Every Array object contains a toString() method that returns a comma-separated
list of array elements as a string. Before adding to the list, each element is converted to
a string. The toString() method of all arrays are called in the example to print their
contents.
A trailing comma in the array literal is ignored. The following two array literals are
considered the same. Both have three elements:
var empIds1 = [10, 20, 30]; // Without a trailing comma. empIds1.length is 3
var empIds2 = [10, 20, 30,]; // Same as [10, 20, 30]. empIds2.length is 3
The elements in the array literal are indexed properties of the array object. For a
dense array, the first element is assigned an index of 0, the second an index of 1, the third
an index of 3, and so on. I will discuss the indexing scheme for sparse arrays shortly.
Consider the following dense array with three elements. Figure 7-1 shows the element's
values and their indexes in the array.
var names = ["Fu", "Li", "Ho"]
0
1
2
Indexes
Values
Fu
Li
Ho
Figure 7-1. Array elements and their indexes in a three-element dense array
You can access the elements of an array the same way you access properties of an
object. The only difference will be that the property name for the element is an integer.
For example, in the names array, names[0] refers to the first element "Fu" , names[1] refers
to the second element "Li" , and names[2] refers to the third element "Ho" . The
following code creates a dense array and uses a for loop to access and print all elements
of the array:
// Create an array with three elements
var names = ["Fu", "Li", "Ho"]
// 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
Search WWH ::




Custom Search