js数组的forEach方法能不能修改数组的值

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

 

 

posted @ 2019-04-01 10:04  Ryan_Yue  阅读(8746)  评论(3编辑  收藏  举报