The forEach() method calls a provided function once for each element in an array.
The forEach() method calls a provided function once for each element in an array.
forEach() does not run the function for array elements without values.
array.forEach(function(currentValue, index, arr), thisValue)
Parameter | Require | Description |
---|---|---|
function(currentValue, index, arr) | Required. | A function to be run for each element in the array. |
thisValue | Optional. | A value to be passed to the function to be used as its "this" value.If this parameter is empty, the value "undefined" will be passed as its "this" value |
For function(currentValue, index, arr)
Argument | Require | Description |
---|---|---|
currentValue | Required. | The value of the current element |
index | Optional. | The array index of the current element |
arr | Optional. | The array object the current element belongs to |
List each item in the array:
var numbers = [4, 9, 16, 25]; function myFunction(item, index) { console.log( "index[" + index + "]: " + item + "\n"); } numbers.forEach(myFunction);/*from w w w . ja v a 2 s. c o m*/ //Get the sum of all the values in the array: var sum = 0; var numbers = [6, 4, 2, 3]; function myFunction1(item) { sum += item; console.log( sum ); } numbers.forEach(myFunction1); //Multiply all the values in array with a specific number: var numbers = [6, 4, 2, 3]; function myFunction2(item,index,arr) { arr[index] = item * 10; console.log(numbers); } numbers.forEach(myFunction2);