Array forEach() Method - Javascript Array

Javascript examples for Array:forEach

Description

The forEach() method calls a function once for each element in an array, in order.

Syntax

array.forEach(function(currentValue, index, arr), thisValue)

Parameter Values

Parameter Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.
Argument Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arrOptional. The array object the current element belongs to
thisValue Optional. A value to be passed to the function to be used as its "this" value.

Return Value:

undefined

The following code shows how to multiply each item in the array:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<p>Multiply with: <input type="number" id="multiplyWith" value="10"></p>

<button onclick="numbers.forEach(myFunction)">Test</button>

<p>Updated array: <span id="demo"></span></p>

<script>
var numbers = [65, 44, 12, 4];//w  w w . j a va  2  s  . c  o  m

function myFunction(item,index,arr) {
    arr[index] = item * document.getElementById("multiplyWith").value;
    demo.innerHTML = numbers;
}
</script>

</body>
</html>

Related Tutorials