Alter and Assign Object Without Side Effects

前端 未结 7 1345
盖世英雄少女心
盖世英雄少女心 2020-11-28 14:27

I currently have the following code:

var myArray = [];
var myElement = {
  id: 0,
  value: 0
}

myElement.id = 0;
myElement.value = 1;
myArray[0] = myElement         


        
相关标签:
7条回答
  • 2020-11-28 15:04

    You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

    myElement.id = 244;
    myElement.value = 3556;
    myArray[0] = $.extend({}, myElement); //for shallow copy or
    myArray[0] = $.extend(true, {}, myElement); // for deep copy
    

    or

    myArray.push({ id: 24, value: 246 });

    0 讨论(0)
提交回复
热议问题