forEach 数组循环方法之一, 包含两个参数,
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | 必需。 数组中每个元素需要调用的函数。函数参数。
| ||||||||
thisValue | 可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值 |
只包含第一个参数,可以使用箭头函数或者普通函数:
var arr = [1, 2, 3];
arr.forEach(function(curr, index, arr){
console.log(curr, index, arr)
})
curr, index, arr 输出为:
1 0 [1, 2, 3]
2 1 [1, 2, 3]
3 2 [1, 2, 3]
包含二个参数时,只能使用普通函数: 第二个参数可选
var arr = [1, 2, 3];
arr.forEach((curr, index, arr){
// 此时的this指的是,forEach 第二个参数,[4, 5, 6];
// 如果使用 箭头函数,this 会向上查找,指向有问题
console.log(curr, index, arr, this)
}, [4, 5, 6])
输出内容
1 0 [1, 2, 3] [4, 5, 6]
2 1 [1, 2, 3] [4, 5, 6]
3 2 [1, 2, 3] [4, 5, 6]