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, 4]
2 1 [1, 2, 3, 4]
3 2 [1, 2, 3, 4]
包含二個參數時,只能使用普通函數: 第二個參數可選
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]