Java Reference
In-Depth Information
print("names.length = " + names.length);
for(var prop in names) {
print("names[" + prop + "] = " + names[prop]);
}
names.length = 3
names[0] = Fu
names[2] = Lo
names.length = 3
names[0] = Fu
names[1] = Do
names[2] = Lo
The following are more examples of sparse arrays. The comments explains the
arrays:
var names = [,]; // A sparse array. length = 1 and no elements
names = [,,]; // A sparse array. length = 2 and no elements
names = [,,,]; // A sparse array. length = 3 and no elements
names = [,,,7,,2]; // A sparse array. length = 6 and 2 elements
Can you tell the difference between the following two arrays?
var names1 = [,,];
var names2 = [undefined,undefined];
Both arrays have
length
2. The array named
names1
is a sparse array. The elements
at index 0 and 1 in
names1
do not exist. Reading
names1[0]
and
names1[1]
will return
undefined
. The array named
names2
is a dense array. The elements at index 0 and 1 in
names2
exist and both are set to
undefined
. Reading
names2[0]
and
names2[1]
will return
undefined
.
How do you know whether an array is sparse? There is no built-in method in the
Array
object to check for a sparse array. You will need to check it yourself keeping in
mind that if a property name that is an index (from 0 to
length)
does not exist in the
array, it is a sparse array. I will discuss few ways to check for a sparse array in the section
Iterating Over Array Elements
.
Using the Array Object
Nashorn contains a built-in function object called
Array
. It is used to create and
initialize an array. It can be called as a function or a constructor. Its use as a function or a
constructor works the same way. Its signature is:
Array(arg1, arg2, arg3,...)
Search WWH ::
Custom Search