Js change object inside array in for each loop

后端 未结 5 1762
广开言路
广开言路 2020-12-18 19:43

I want to change the current object in for each loop and it does not work, Why it is not working and how can i do this?

var arr = [{num: 1}, {num: 2}];

arr.         


        
5条回答
  •  鱼传尺愫
    2020-12-18 20:39

    You are changing the local reference item in the callback function.

    To change array contents, you need to use the array index and assign new reference to it, as shown in below

    arr.forEach(function(item, i) {
      arr[i] = {somethingElse: 1} //using index, change the reference in array
    });
    

提交回复
热议问题