JavaScript Array forEach() 方法
示例 1
为 fruits 中的每个元素调用一个函数
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
自己动手试一试 »
描述
forEach()
方法为数组中的每个元素调用一个函数。
forEach()
方法不会对空元素执行函数。
数组迭代方法
语法
array.forEach(function(currentValue, index, arr), thisValue)
参数
function() | 必需。 为每个数组元素运行的函数。 |
currentValue | 必需。 当前元素的值。 |
index | 可选。 当前元素的索引。 |
arr | 可选。 当前元素所属的数组。 |
thisValue | 可选。默认 undefined 。作为其 this 值传递给函数的值。 |
返回值
undefined |
更多示例
计算和
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
自己动手试一试 »
将每个元素相乘
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
自己动手试一试 »
浏览器支持
forEach()
是 ECMAScript5 (ES5) 的特性。
自 2013 年 7 月以来,所有现代浏览器都完全支持 ES5 (JavaScript 2009)
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
2012 年 9 月 | 2012 年 9 月 | 2013 年 4 月 | 2012 年 7 月 | 2013 年 7 月 |