javascript arrays and methods for deep copying of objects (copying arrays or copying objects)

Today, I encountered an example of copying JS reference types. Copy A to B, and modifying the value in B or A will not affect the data of the other party. I tried to copy it by direct assignment, but I am trying to directly assign the reference type. After the copy is completed, the two variables are related to each other, one changes, the other will also change, so let's understand the deep copy of the array or object.

1. One-dimensional array deep copy method:

1. for loop to achieve deep copy of array

     function copy(array){
        let res=[];
        for(let i=0;i<array.length;i++){
          res.push(array[i]);
        }
        return res;
      }
      var arr1 = [1,2,3,4,5 ];
      var arr2 = copy (arr1);
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[1, 2, 3, 4, 5]
      arr2[0]=6;
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[6, 2, 3, 4, 5]

2. The slice method implements a deep copy of an array

      var arr1 = [1,2,3,4,5 ];
      var arr2 = arr1.slice (0 );
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[1, 2, 3, 4, 5]
      arr2[0]=6;
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[6, 2, 3, 4, 5]

3. The concat method implements a deep copy of the array

      var arr1 = [1,2,3,4,5 ];
      var arr2 = arr1.concat ();
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[1, 2, 3, 4, 5]
      arr2[0]=6;
      console.log(arr1); //[1, 2, 3, 4, 5]
      console.log(arr2); //[6, 2, 3, 4, 5]

2. Deep copy of simple objects

1.for loop

    function copyobj(obj){
        let res={};
        for(var key in obj){
          res[key]=obj[key];
        }
        return res;
      }
      var obj1 = {
        name:"zz",
        sex:"man",
        age:18
      }
      var obj2 = copyobj (obj1);
      console.log(obj1); //{name: "zz", sex: "man", age: 18}
      console.log(obj2); //{name: "zz", sex: "man", age: 18}
      obj1['name']="pp";
      console.log(obj1); //{name: "pp", sex: "man", age: 18}
      console.log(obj2); //{name: "zz", sex: "man", age: 18}

The above methods are more practical for one-dimensional arrays and simple objects, but not for multi-dimensional arrays.

Three, multidimensional array copy

1. Use jq's $.extend(true, target, obj)

      var arr1 = [1, 2, [3, 4], {a: 5, b: 6}, 7 ],
      arr2 = $.extend(true, [], arr1);

2. Convert to json and then convert to object to achieve a deep copy of the object (simple or complex objects can be)

     var obj1 = {
        name:"zz",
        sex:"man",
        age:18,
        parent:{
          name: 'Rattz1',
          age: 50,
        },
      }
      var obj2 = JSON.parse(JSON.stringify(obj1));
      obj1['age']=30;
      obj1['parent']['age']=60;
      console.log(obj1);
      console.log(obj2);

The result of execution is:

3. Prototype extension (for multidimensional arrays or complex objects)

 Object.prototype.clone = function() {
        var obj = {};

        for(var i in this) {
            if(typeof this[i] !== "object") {
                obj[i] = this[i];
            } else {
                obj[i] = this[i].clone();
            }
        }

        return obj;
    }

    Array.prototype.clone = function() {
        var len = this.length,
            arr = [];

        for(var i = 0;i < len;i++) {
            if(typeof this[i] !== "object") {
                arr.push(this[i]);
            } else {
                arr.push(this[i].clone());
            }
        }
        return arr;
    }

    // Test Object 
    var obj1 = {
        name: 'Rattz',
        age: 20,
        parent:{
          name: 'Rattz1',
          age: 50,
        },
        hello: function () {
            return "I'm " + name;
        }
    };
    var obj2 = obj1.clone();
    obj2.parent.age++;
    console.log(obj1);
    console.log(obj2);

    //测试2 Array
    var fun = function(log) {console.log},
    arr1 = [1, 2, [3, 4], {a: 5, b: 6}, fun],
    arr2 = arr1.clone();
    arr1 [ 0] = 10 ;
    arr2[2][1]=13;
    console.log(arr1);
    console.log(arr2);

The result of execution is:

Reference: https://blog.csdn.net/github_34514750/article/details/56677750

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325930836&siteId=291194637