You can of course use an arrow function if your implementation supports ES6+:
myStringArray.forEach( s => {
// ... do something with s ...
} );
Unlike for
...of
, .forEach
only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. It also distinguishes between missing elements and elements that are actually set to undefined
; for the latter, it will still call the function, passing undefined
as the argument. If this is how you want to handle sparse arrays, .forEach
may be the way to go even if your interpreter supports for
...of
.
One advantage of this approach is that you can choose how to handle sparse arrays; thearrays. The above code will run the body of the loop the full length
times, with s
set to undefined
for any missing elements, just like for
..of
. If; if you instead want to handle only the actually-present elements of a sparse array, like .forEach
, you can add a simple in
test on the index:
AssigningDepending on your implementation's optimizations, assigning the length value to the local variable (as opposed to including the full myStringArray.length
expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%through.
You may see the length caching done in the loop initialization clause, like this:
myStringArray.forEach( function(s, i) => {
// ... do something with s and i ...
});
for
...of
doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array
(and not one of the other iterable types for
..of
works for other iterable types which may not have this methodon), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that: