一、定义
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
二、语法
array.forEach(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr)必需。 数组中每个元素需要调用的函数。函数参数:
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。当前元素所属的数组对象。 |
thisValue可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值
应用场景1:数组迭代
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt = txt + value + "<br>";
}
//结果
45
4
9
16
25
应用场景2:数组、对象遍历
let arr = [1,23,45,6,7,]
arr.forEach((item)=>{
console.log(item*2)
})
//结果
2
46
90
12
14