Shallow Copy vs Deep Copy

128 阅读2分钟

深拷贝和浅拷贝是只针对Object和Array这样的引用数据类型的。

引用数据类型的特点:存储的是该对象在栈中引用,真实的数据存放在堆内存里

DEEP copying:如果你有你个数组或对象在数组里(也就是嵌套对象Nested Object),你需要做深拷贝。新对象跟原对象不共享内存,修改新对象不会改到原对象。

浅拷贝:我们复制的只是指向数组的指针或指向原始数组内对象的指针,当我们复制数组时,我们只是将指针复制到原始数组,新旧对象共享内存,当原对象包含子对象时,子对象的改变会使原对象一同改变。

var original = [true, true, undefined, false, null];

// slice
var copy1 = original.slice(0);


// spread operator
var copy2 = [...original];
console.log(copy1, copy2);


// DEEP copying:如果你有你个数组或对象在数组里(也就是嵌套对象Nested Object),你需要做深拷贝
var deepArray = [["Code"]];
var shallowCopy = deepArray.slice(0);
// 浅拷贝:我们复制的只是指向数组的指针或指向原始数组内对象的指针,当我们复制数组时,我们只是将指针复制到原始数组
shallowCopy[0].push("is great");
console.log(deepArray[0], shallowCopy[0])

var deepCopy = JSON.parse(JSON.stringify(deepArray));

deepCopy[0].push("is great");
console.log(deepArray[0], deepCopy[0])
    Deep Copy methods
    1. JSON.parse(JSON.stringify())
    2. Service Workers postMessage() onmessage
    3. History API history.pushState(obj, title) history.state
    4. Notification API new Notification("title", {data: obj} ).data
    5. Build a custom recursive function
  
let shallowArr = [123, 
                          'bob', 
                          true, 
                          null, 
                          undefined];
        
        let deepArr = [123, 
                       'bob', 
                       true, 
                       ['Hank', 'Brent', 'Lacy'], 
                       {'Rouleau':'Dog River', 
                        'Wilcox': 'Woolerton'}
                      ];
        
        let deepObj = {
            'characters': ['Wanda','Davis','Emma','Karen'],
            'places': ['Corner Gas','Ruby','Foo Mart'],
            'grad68': false,
            'seasons': 5
        }
        
        let newObj = {...deepObj};
        //newObj.places[0] = 'Ottawa'; //changed inside ref.
        //newObj.places = ['Ottawa', 'Calcutta']; //new ref
        console.log(newObj, deepObj);
        let otherObj = JSON.parse(JSON.stringify(deepObj));
        otherObj.places[0] = 'Ottawa';
        console.log(otherObj, deepObj);
    Shallow Copy Method examples
    1. arr1.slice(0)
    2. [].concat(arr1)
    3. Spread Operator
    4. Object.create({}, obj)
    5. Object.assign({}, obj)
    6. Array.from(arr1)
 let s = 'steve';
        let g = s;
        s = 'new value';
        console.log(s, g);
        
        let arr = Array.from(shallowArr);
        // let arr1 = [...shallowArr];
        shallowArr[0] = 456;
        console.log(arr, shallowArr);

image.png 具体是选择深拷贝还是浅拷贝根据工作需求而定。