And an array of objects with deep copy shallow copy

Object assignment:

1.var objOld = {a:1,b:2},

  objNew = objOld;

    objOld.a = 5;

    At this time, output: objOld = {a: 5, b: 2};

          objNew = {a:5,b:2};

    Description Modify the value objNew will affect the value of objOld

2.var objOld = {a:1,b:2},

    objNew = Object.assign({},objOld);

    objOld.a = 5;

    At this time, output: objOld = {a: 5, b: 2};

          objNew = {a:1,b:2};

    Description objNew modified value does not affect the value of objOld, but this method can only modify the value of the first layer, you will not be able to modify the deep, such as:

    var objOld = {a:1,b:{c:2}}, objOld.b.c = 5;

    At this time, output: objOld = {a: 1, b: {c: 5}};

          objNew = {a:1,b:{c:5}};

3.var objOld = {a:1,b:{c:2}},

  objNew = JSON.parse(JSON.stringify(objOld ));

   objOld.b.c = 5;

   At this time, output: objOld = {a: 1, b: {c: 5}};

      objNew = {a:1,b:{c:2}};

   Description deep modify this object, it will not change the value of the original object

 

Array assignment:

1. was arrOld = [1],

  arrNew = arrOld ;

    arrNew [0]++;

    At this time, output: arrOld = [2];

          arrNew = [2];

    Modify the value arrNew will affect the value of arrOld

2. does not affect the value of the old three methods:

(1) The method can be used jquery:

  was arrOld = [1],

    arrNew = $.extend(true,{},arrOld );

  arrNew [0]++;

  At this time, output: arrOld = [1];

       arrNew = [2];

(2) was arrOld = [1],

    arrNew = arrOld .concat();

    arrNew [0]++;

  At this time, output: arrOld = [1];

      arrNew = [2];

(3) calling a function method:

  was arrOld = [1,2],

    arrNew = [3,4];

  function change(){

    arrOld[0] = 4;

    was c = arrOld;

    arrOld = arrNew ;

    arrNew = c;

  }

  At this time, output: arrOld = [4,2];

      arrNew = [3,4];

3.vue framework: Vue.set

  Vue.set (target, propertyName / index, value) can be, deep principle, free to explore 

Guess you like

Origin blog.csdn.net/sunfrw/article/details/90476280