JavaScript - Arrays - forEach

javascript-arrays

// JavaScript - Array.prototype.forEach()
The forEach() method executes a provided function once per array element.

arr.forEach(callback[, thisArg])

callback: Function to execute for each element, taking three arguments: 
1. currentValue: The current element being processed in the array.
2. index: The index of the current element being processed in the array.
3. array: The array that forEach() is being applied to.

thisArg: Optional.  Value to use as this when executing callback.

The forEach() method executes the provided callback once for each element 
present in the array in ascending order. It is not invoked for index properties 
that have been deleted or are uninitialized (i.e. on sparse arrays).

If you are testing the array elements for a predicate and need a Boolean return 
value, you can use every() or some() instead. If available, the new methods 
find() or findIndex() can be used for early termination upon true predicates as 
well.

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License