English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
forEach()The method executes the provided function (callback function) once for each array element.
There is no other way to stop or interrupt the loop except by throwing an exception.forEach()Loop.
If you want to terminate early, you can do so by using the following method:
A simple loop
Onefor......ofLoop
array.forEach(callback, thisArg)
var fruits = ["Apple", "Mango", "Banana", "Orange"]; var result = document.getElementById("result"); fruits.forEach(function(element) { result.innerHTML += element + "<br>"; });Test and see‹/›
The numbers in the table specify the first browser version that fully supports the forEach() method:
Method | |||||
forEach() | Is | 1.5 | Is | Is | 9 |
Parameter | Description |
---|---|
callback | A function that is run for each element in the array. Function parameters:
|
thisArg | (Optional) ExecuteCallbackIs used asThisObject |
Return value: | Undefined |
---|---|
JavaScript version: | ECMAScript 5 |
The callback function can contain at most3A parameter:
var fruits = ["Apple", "Mango", "Banana", "Orange"]; var result = document.getElementById("result"); fruits.forEach(function(element, index, array) { result.innerHTML += index + : "" + element + "<br>"; });Test and see‹/›
Get the sum of all values in the array:
var nums = [2, 5, 10, 5, 10, 28]; var sum = 0; nums.forEach(function(element) { sum += element; }); document.getElementById("result").innerHTML = sum;Test and see‹/›
Get the average value of the values in the array:
var nums = [2, 5, 10, 5, 10, 28]; var sum = 0; nums.forEach(function(element) { sum += element; }); document.getElementById("result").innerHTML = sum / nums.length;Test and see‹/›
Convert forEach loop to for loop:
var nums = [2, 5, 10, 5, 10, 28]; var sum = 0; for (let i = 0; i < nums.length;++) { sum = sum + nums[i]; }); document.getElementById("result").innerHTML = sum;Test and see‹/›