Java Reference
In-Depth Information
The following code passes a nonnumeric argument to the Array constructor that
creates an array with the passed argument as its sole element and sets the length of the
array to 1:
var names1 = new Array("Fu"); // Creates an array with one element "Fu"
var names2 = new Array(true); // Creates an array with one element true
Passing Two or More Arguments
When two or more arguments are passed to the Array constructor, it creates a dense array
with the specified arguments. The length is set to the number of arguments passed. The
following statement creates an array with three passed arguments and sets the length to 3:
var names = new Array("Fu", "Li". "Do");
You cannot create a sparse array using the Array constructor. Using consecutive
commas or trailing commas in the Array constructor throws a SyntaxError exception:
var names1 = new Array("Fu", "Li",, "Do"); // A SyntaxError
var names2 = new Array("Fu", "Li", "Do", ); // A SyntaxError
You can create a sparse array by adding elements at noncontiguous indexes or
deleting the existing elements, so the indexes become noncontiguous. I will discuss
deleting the elements of an array in the next section. The following code creates a dense
array and adds a noncontiguous element to make it a sparse array:
// Creates a dense array with elements at indexes 0 and 1.
var names = new Array("Fu", "Li"); // names.length is set to 2
print("After creating the array: names.length = " + names.length);
// Add an element at index 4, skipping index 2 and 3.
names[4] = "Do"; // names.length is set to 5, making names a sparse array
print("After adding an element at index 4: names.length = " + names.length);
for(var prop in names) {
print("names[" + prop + "] = " + names[prop]);
}
After creating the array: names.length = 2
After adding an element at index 4: names.length = 5
names[0] = Fu
names[1] = Li
names[4] = Do
 
Search WWH ::




Custom Search