The difference between shallow and deep copies

How to distinguish the deep copy from the shallow copy? In simple terms, suppose B copies A, and when A is modified, see whether B changes. If B also changes, it is A shallow copy, which is short.

Shallow copy

letA =,1,2,3,4 [0], b = a; console.log(a===b); a[0]=1; console.log(a,b);Copy the code

Finally screenshot complete copy really cool, I mainly show you how to make a deep copy

Deep copy implementation

1. Deep copy is implemented recursively

    functionDeepClone1 (obj) {var objClone = array.isarray (obj)? [] : {}; // The deep copy cannot be empty and is an object orif (obj && typeof obj === "object") {
                for (key in obj) {
                    console.log(key,'key')
                    if (obj.hasOwnProperty(key)) {
                        if (obj[key] && typeof obj[key] === "object") {
                            objClone[key] = deepClone1(obj[key]);
                        } else{ objClone[key] = obj[key]; }}}}else{
                    console.log(key,'ke11y')}returnobjClone; } var ma={ma1:2} var ma=[2,3,3] deepClone1Copy the code

2 Implement deep copy recursively

/ Deep copy array objects through the built-in JSON object of JSfunction deepClone2(obj) {
  var _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj);
  return objClone;
}
Copy the code

3, through jQuery extend method to achieve deep copy

Var array = [1, 2, 3, 4]; var newArray = $.extend(true,[],array);
Copy the code

3, through jQuery extend method to achieve deep copy

Var array = [1, 2, 3, 4]; var newArray = $.extend(true,[],array);
Copy the code

4 the Object. The assign () copies

The method is a deep copy if the object has only the first level properties and no second level properties, but a shallow copy if the object has the second level properties.

The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Copy the code