js中的foreach詳細用法詳解

forEach 數組循環方法之一, 包含兩個參數,

參數 描述
function(currentValue, index, arr) 必需。 數組中每個元素需要調用的函數。函數參數。
參數 必需。初始值, 或者計算結束後的返回值
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]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章