Alter and Assign Object Without Side Effects

前端 未结 7 1344
盖世英雄少女心
盖世英雄少女心 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 14:46

    If you're using jQuery, you can use extend

    myElement.id =0;
    myElement.value=1;
    myArray[0] = $.extend({}, myElement);
    
    myElement.id = 2;
    myElement.value = 3;
    myArray[1] = $.extend({}, myElement);
    
    0 讨论(0)
  • 2020-11-28 14:47

    Try this instead:

    var myArray = [];
    
    myArray.push({ id: 0, value: 1 });
    myArray.push({ id: 2, value: 3 });
    

    or will this not work for your situation?

    0 讨论(0)
  • 2020-11-28 14:47

    That's because object values are passed by reference. You can clone the object like this:

    var myArray = [];
    var myElement = {
      id: 0,
      value: 0
    }
    
    myElement.id =0;
    myElement.value=1;
    myArray[0] = myElement;
    
    var obj = {};
    obj = clone(myElement);
    obj.id = 2;
    obj.value = 3; 
    
    myArray[1] = obj;
    
    function clone(obj){
      if(obj == null || typeof(obj) != 'object')
        return obj;
    
      var temp = new obj.constructor(); 
      for(var key in obj)
        temp[key] = clone(obj[key]);
    
      return temp;
    }    
    
    console.log(myArray[0]);
    console.log(myArray[1]);
    

    Result:

     - id: 0
     - value: 1
     - id: 2
     - value: 3
    
    0 讨论(0)
  • 2020-11-28 14:54

    You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.

    0 讨论(0)
  • 2020-11-28 15:00

    Objects are passed by reference.. To create a new object, I follow this approach..

    //Template code for object creation.
    function myElement(id, value) {
        this.id = id;
        this.value = value;
    }
    var myArray = [];
    
    //instantiate myEle
    var myEle = new myElement(0, 0);
    //store myEle
    myArray[0] = myEle;
    
    //Now create a new object & store it
    myEle = new myElement(0, 1);
    myArray[1] = myEle;
    
    0 讨论(0)
  • 2020-11-28 15:03

    This is a textbook case for a constructor function:

    var myArray = [];
    
    function myElement(id, value){
        this.id = id
        this.value = value
    }
    
    myArray[0] = new myElement(0,1)
    myArray[1] = new myElement(2,3)
    // or myArray.push(new myElement(1, 1))
    
    0 讨论(0)
提交回复
热议问题