Java Reference
In-Depth Information
The for loop does not work if you have a sparse array. If you try accessing the
missing elements in the sparse array, it will return undefined that does not tell you
whether the element is missing or the value for the existing element is undefined . You
can get rid of this limitation by using the in operator to check if the index being iterated
exists. If the index exists, the element exists; if the index does not exist, it is a missing
element in a sparse array. The following code demonstrates this approach:
// Create a sparse array with an element set to undefined
var names = ["Fu", "Li", , "Do", undefined, , "Lu"];
// Use a for lop to iterate all elements of an array
for (var i = 0, len = names.length; i < len; i++) {
// Check if the index being visited exists in the array
if (i in names) {
print("names[" + i + "]=" + names[i]);
}
}
names[0]=Fu
names[1]=Li
names[3]=Do
names[4]=undefined
names[6]=Lu
Consider the following code. It creates a sparse array with only one element. The
array is the biggest possible array in Nashorn and the element is added at the last index
in the array. In practice, you will never have this big array. I used it just to prove the point
that using the for loop is not the most efficient way to access all elements in a sparse array:
// Create an empty array
var names = new Array();
// Add one element to the end of the biggest possible array
names[4294967294] = "almost lost";
// Use a for loop to iterate all elements of an array
for (var i = 0, len = names.length; i < len; i++) {
// Check if the index being visited exists in the array
if (i in names) {
print("names[" + i + "]=" + names[i]);
}
}
Search WWH ::




Custom Search