如果要使用数组的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]