javascript 数组以及对象的深拷贝(复制数组或复制对象)的方法

时间:2021-05-20 19:53:24

今天遇到一个拷贝JS引用类型的例题,把A拷贝到B,在B或A中修改值不会影响对方的数据,我试着直接赋值方式进行拷贝,但是在对引用类型进行直接赋值方式的拷贝完成后,两个变量是相互联系的,一个改变,另一个也会跟着改变,因此我们就来了解下数组或对象的深拷贝。

一、一维数组深拷贝方法:

1.for循环实现数组的深拷贝

     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.slice方法实现数组的深拷贝

      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.concat方法实现数组的深拷贝

      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]

二、简单对象的深拷贝

1.for循环

    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}

上面几种方法对于一维数组和简单对象来说比较实用,对于多维数组就不适用了。

三、多维数组拷贝

1.使用jq的$.extend(true,target,obj)

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

2.转换成json再转换成对象实现对象的深拷贝(简单或者复杂的对象都可以)

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

执行的结果为:

javascript 数组以及对象的深拷贝(复制数组或复制对象)的方法

3.原型扩展(适用于多维数组或复杂对象)

 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;
    }

    //测试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);

执行的结果为:

javascript 数组以及对象的深拷贝(复制数组或复制对象)的方法

参考:https://blog.csdn.net/github_34514750/article/details/56677750