Java Reference
In-Depth Information
Using the for loop in this example is very inefficient, because it has to visit
4294967293 indexes, before it can get to the last one that has the value. It takes too long
to get to just one element of the array. I will solve this slow performing for loop problem
shortly using the for..in loop.
Using the forEach() Method
The Array.prototype object contains a method named forEach() that invokes a callback
function for each element in the array in ascending order. It visits only the existing
elements in the sparse array. Its signature is:
forEach (callbackFunc [, thisArg])
Here, callbackFunc is a function that is called once for each element in the array in
ascending order. It is passed three arguments: the value of the element, the index of the
element, and the object being iterated. The thisArg is optional; if it is specified, it is used
as the this value for each invocation to callbackFunc .
The forEach() method sets the range of indexes it will visit before it starts executing.
If elements are added beyond that range during its execution, those elements are not
visited. If elements in the initially set range are deleted, those elements are not
visited either:
// Create a sparse array with an element set to undefined
var names = ["Fu", "Li", , "Do", undefined, , "Lu"];
// Define the callback function
var visitor = function (value, index, array) {
print("names[" + index + "]=" + value);
};
// Print all elements
names.forEach(visitor);
names[0]=Fu
names[1]=Li
names[3]=Do
names[4]=undefined
names[6]=Lu
If you use the forEach() method to visit a big sparse array, you will have the same
problem as using the for loop that I discussed in the previous section.
 
Search WWH ::




Custom Search