javascript for loop changes original list variable

后端 未结 3 1592
说谎
说谎 2021-01-26 20:40

I have a collection of objects called the response and I am creating another variable called object that\'s an empty object and creating object.array a

3条回答
  •  暖寄归人
    2021-01-26 20:51

    You are just copying them by reference which means they are in the same location in memory so whatever you try to modify one of them the other will get modified in order to prevent this you should pass you in either of these ways:

    1. Using Array.from()
    object.array = Array.from(response);
    
    1. Using slice()
    object.array = response.slice();
    
    1. Using spread syntax (...)
    object.array = [...response];
    
    1. Using JSON.parse/JSON.strigify
    object.array = JSON.parse(JSON.stringify(response));
    

    But in your particular case, only the last option will work as expected since you got a nested array, you need a deep copy of your element.

    So the final result should be something like this:

    function runThisLoop() {
    
      var response = [{
          name: 'Name A',
          age: 2
        },
        {
          name: 'Name B',
          age: 7
        }
      ]
    
    
      var object = {}
      object.array = JSON.parse(JSON.stringify(response));
    
      for (var val of object.array) {
        val.age = null
      }
    
      console.log("response", response)
      console.log("object.array", object.array)
    }
    
    runThisLoop()

提交回复
热议问题