Calls a function for each element in fruits:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Try it Yourself »
The forEach()
method calls a function for each element in an array.
The forEach()
method is not executed for empty elements.
array.forEach(
function(currentValue, index, arr), thisValue)
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
undefined |
Compute the sum:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Try it Yourself »
Multiply each element:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
Try it Yourself »
forEach()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!