如果要使用數組的forEach()方法對其改值時,需要直接通過arr[i]這種方式來更改。
請看下面代碼:
// 數組改值 let arr = [1,3,5,7,9]; arr.forEach(function(item){ item = 30; }) console.log(arr); //輸出 (5) [1, 3, 5, 7, 9]
顯然沒有達成目的,下邊這樣寫可以實現
// 數組改值 let arr = [1,3,5,7,9]; arr.forEach(function(item,index,arr){ arr[index] = 30; }) console.log(arr); //輸出 (5) [30, 30, 30, 30, 30]