Javascript examples for Array:forEach
The forEach() method calls a function once for each element in an array, in order.
array.forEach(function(currentValue, index, arr), thisValue)
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 |
arr | Optional. 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. |
undefined
The following code shows how to multiply each item in the array:
<!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>