javascript for loop changes original list variable

后端 未结 3 1624
说谎
说谎 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 21:16

    This line object.array = response is just pointing to same memory location. Create a fresh copy of the object and update value in that

    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()

提交回复
热议问题