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) 必需。为数组中的每个元素运行的函数。

函数参数:

参数 描述
currentValue 必需。当前元素的值。
index 可选。当前元素的数组索引。
arr 可选。当前元素所属的数组对象
thisValue

可选。要传递给函数以用作其 "this" 值的值。

如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。

技术细节

返回值: undefined
JavaScript 版本: ECMAScript 5

浏览器支持

所有浏览器都完全支持 forEach() 方法:

Chrome IE Edge Firefox Safari အိုပီယာ
Chrome IE Edge Firefox Safari အိုပီယာ
ထောက်ပံ့ 9.0 ထောက်ပံ့ ထောက်ပံ့ ထောက်ပံ့ ထောက်ပံ့

ပတ်သက်ပြီး စာမျက်နှာ

အစီအစဉ်သတင်းJavaScript အတွေ့အကြုံ

အစီအစဉ်သတင်းJavaScript အတွေ့အကြုံ Const

အစီအစဉ်သတင်းJavaScript အတွေ့အကြုံ စနစ်

အစီအစဉ်သတင်းJavaScript အတွေ့အကြုံ စီးပွား

အစီအစဉ်သတင်းJavaScript အတွေ့အကြုံ အပေါင်း