JavaScript Array forEach()
定义和用法
forEach() 方法按顺序为数组中的每个元素调用一次函数。
注释:对于没有值的数组元素,不执行forEach() 方法。
实例
例子 1
列出数组中的每一项:
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
例子 2
获取数组中所有值的总和:
var sum = 0;
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
document.getElementById("demo").innerHTML = sum;
}
例子 3
对于数组中的每个元素:将值更新为原始值的 10 倍:
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
语法
array.forEach(function(currentValue, index, arr), thisValue)
参数值
| 参数 | 描述 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index, arr) | 必需。为数组中的每个元素运行的函数。
函数参数:
|
||||||||
| thisValue |
可选。要传递给函数以用作其 "this" 值的值。 如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。 |
技术细节
| 返回值: | undefined |
|---|---|
| JavaScript 版本: | ECMAScript 5 |
浏览器支持
所有浏览器都完全支持 forEach() 方法:
| Chrome | IE | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| Chrome | IE | Edge | Firefox | Safari | Opera |
| 支持 | 9.0 | 支持 | 支持 | 支持 | 支持 |