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

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-23
  • 2022-12-23
  • 2021-08-02
  • 2018-11-12
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案