深拷貝&淺拷貝

github源碼:https://github.com/fypShirley...html

看下面的示例瞭解賦值和引用的區別:

賦值:
    var a = 5;
    var b = a;
    b+=3;
    
    console.log(b)//8
    console.log(a)//5 原值沒有發生改變

引用:(對象和函數都是引用的關係)
    var a = [1,2,3];
    var b = a;
    var c = a;
    b.push(4);
    
    console.log(b);//[1,2,3,4]
    console.log(a);//[1,2,3,4] a被影響
    
    c = [1,2,3,4,5];
    console.log(c);//[1,2,3,4,5]
    console.log(a);//[1,2,3,4] a不受影響

淺拷貝:

var obj0= {a:10};
   var obj1= {a:{b:10}};
   
   function copy(obj){//淺拷貝
       var newObj = {};

       for(var attr in obj){
           newObj[attr] = obj[attr];
       }
       return newObj;
   }
   
    var obj2 = copy(obj0);
    var obj3 = copy(obj1);
    obj3.a.b = 20;
    
    console.log(obj0.a);//10 a不受影響
    console.log(obj1.a.b);//20 受影響了,仍是引用

深拷貝:

先看一個遞歸 :
function test(n){
    if(n == 1){
        console.trace()
        return 1;
    }
    return n*test(n-1);
}
console.log(test(4))//1*2*3*4 -> 24
深拷貝利用遞歸的思想:
function deepCopy(obj){//一層層進入,拿到值
   if(typeof obj != 'object'){
       return obj;
   }
   console.trace();
   var newObj = {};

   for(var attr in obj){
       newObj[attr] = deepCopy(obj[attr]);//遞歸
   }
   return newObj;
 }
 var obj4= {a:{b:10}};
 var obj5 = deepCopy(obj4);
 obj5.a.b = 20;
 console.log(obj4.a);//a->{b:10},原數據沒有改變
 console.log(obj5.a);//a->{b:20},

再一個深/淺拷貝的對比

//先聲明一個對象parent:

 var parent = {
   numbers: [1, 2, 3],
   letters: ['a', 'b', 'c'],
   obj: {prop: 1   },
   bool: true
};

// 淺拷貝函數:
function extendCopy(p) {//傳地址
   var c = {};
   for (var i in p) {
       c[i] = p[i];
   }
   c.uber = p;
   return c;
}


// 深拷貝函數:
function deepCopy(p, c) {//傳值
//在拷貝每一個屬性以前,建議使用 hasOwnProperty()來確認不會誤拷貝不須要的繼承屬性。
   c = c || {};
   for (var i in p) {
       //console.log(p.hasOwnProperty(i))
       if (p.hasOwnProperty(i)) {
           if (typeof p[i] === 'object') {
               c[i] = Array.isArray(p[i]) ? [] : {};
               deepCopy(p[i], c[i]);
           } else {
               c[i] = p[i];
           }
       }
   }
   return c;
}

var mydeep = deepCopy(parent);
mydeep.numbers.push(5);
console.log(mydeep.numbers)//[1,2,3,5]
console.log(parent.numbers)//[1,2,3]原數據沒有改變

myshallow.numbers.push(6);
console.log(myshallow.numbers)//[1,2,3,6]
console.log(parent.numbers)//[1,2,3,6原數據改變
console.log(mydeep.numbers)//[1,2,3]
相關文章
相關標籤/搜索