preface

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”. Can you Copy? In many practical work situations, the front-end raiders in the processing of data, often use the data of deep copy and shallow copy, today, by me to share with you the front-end programmers necessary small knowledge of the data of deep copy and shallow copy, I hope to help you in the process of work and learning!

Application scenarios

When you need to send the data as a parameter to another interface, more or less, more or less, there are a few remaining fields are redundant, please ask, at this time what should you do?

Unknown digg friend: That is not easy, just delete unnecessary parameters, so easy!

A:

  • What if you want the same data field after you delete it? Not only will this result in the loss and contamination of the page data, but some of the content on the page will not be displayed
  • If no action is taken, the interface may receive extra parametersBug, resulting in a request error, the correct response data cannot be obtained
  • So, in this caseDeep copyandShallow copyIs very necessary!

Concept: shallow copy and deep copy

What is shallow copy and deep copy?

My personal understanding

  • There are two objects A and B, A is not empty and B is empty, B copies A, we modify A, if the data in BFollow changeThat’s itShallow copy
  • ifThere is no change, that is,Deep copy
  • In a nutshell,Shallow copyAffects the data of the previously copied object, andDeep copyWill not be

Note: Assignment is not the same thing as deep copy and shallow copy, so don’t get confused!

Deep copy and shallow copy are mainly for reference type data, because after the basic data type is assigned, the change of new data does not affect the original data, and they are independent of each other. For reference data type assignments, changes to the new data will affect the original data. In this case, shallow copy and deep copy should be used to define a data that is identical to the original data but does not affect each other.

Difference and Essence

Because the data is stored in memory, and when we call the data, we call the data through the address

For shallow copy, such as an array (objects), a copy as long as we have modified the array, so the original array would also be affected, it is because they refer to the same address data, copy is not to copy an array to create independent memory, just copy to be copied array data address to copy an array.

Deep copy, on the other hand, creates a separate memory for the copied array and copies the contents of the copied array into each other, independent of each other.

The practice part

An assignment operation for a primitive data type

There are only seven built-in data types in JavaScript: NULL, undefined, Boolean, number, String, Bigint, and Symbol. Basic data types include number, String, Boolean, undefined, and NULL. After the basic data types are assigned, the two variables do not affect each other.

    let a = Awesome!;
    let b = a; 
    a = 777;
    
    console.log(a); / / 777
    console.log(b); / / 666
Copy the code

By assigning a to B, the value of B is 666, and then changing the value of A without affecting the value of the b space.

An assignment that references a data type

    let arr = [1.2.3];
    let anotherArr = arr;
    arr.pop(2);
    console.log(arr); / / (2) [1, 2]
    console.log(anotherArr); / / (2) [1, 2]
    console.log(arr === anotherArr); // true
Copy the code

Initialize an array named arr and assign arR to anotherArr. At this point, arR and anotherArr already share a memory address. After removing arR from index = 2, AnotherArr is also changed, and the final output is the same. Use === to determine whether the value and type are exactly the same, and the reference address of the result is exactly the same.

Shallow copy

You can use the assign method on the system-supplied constructor Object. The Object.assign() method is used to assign the values of all enumerable properties from one or more source objects to target objects. It will return the target object. If an attribute in the target object has the same key, the attribute is overwritten by an attribute in the source object. Properties of subsequent source objects similarly override properties of previous source objects.

Grammar:

    Object.assign(target object),... Sources (Source object)Copy the code

Here’s an example:

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

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

    // Try changing the copy object
    returnedTarget.b = 10;
    
    // The result changed accordingly
    console.log(target); // Object { a: 1, b: 10, c: 5 }
    console.log(returnedTarget); // Object { a: 1, b: 10, c: 5 }
    console.log(target === returnedTarget); // true
Copy the code

For deep copies, an alternative approach is needed because object.assign () copies (enumerable) property values.

Deep copy

Digg friend passing by at this time: how to achieve deep copy?

Here are two methods for your reference:

    // deep clone (deep clone does not consider functions)
    function deepClone(obj, result) {
        var result = result || {};
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                if (typeof obj[prop] == 'object'&& obj[prop] ! = =null) {
                    // Reference value (obj/array) and not null
                    if (Object.prototype.toString.call(obj[prop]) == '[object Object]') {
                        / / object
                        result[prop] = {};
                    } else {
                        / / array
                        result[prop] = [];
                    }
                    deepClone(obj[prop], result[prop])
                } else {
                    // The original value or func
                    result[prop] = obj[prop]
                }
            }
        }
        return result;
    }

    // Depth clone is for reference values
    function deepClone(target) {
        if (typeof(target) ! = ='object') {
            return target;
        }
        var result;
        if (Object.prototype.toString.call(target) == '[object Array]') {
            / / array
            result = []
        } else {
            / / object
            result = {};
        }
        for (var prop in target) {
            if (target.hasOwnProperty(prop)) {
                result[prop] = deepClone(target[prop])
            }
        }
        return result;
    }
Copy the code

The above two functions, one with two parameters and the other with one parameter, both implement data deep cloning in a recursive manner, so that no matter what changes are made to one copy object, the other is truly independent of each other and do not affect each other.

conclusion

  1. Assignment is assignment, copy is copy, don’t confuse assignment with copy, they are not the same thing

  2. Shallow copy, when the data in the object or array is of primitive type, the two data are completely independent of each other. If the value in the object or array is of reference type, the value in the reference type will keep the same memory address

  3. Shallow copy the common system-provided assign method on the Object constructor

  4. Deep copy needs to write its own function to achieve, and the two data out of the deep copy is completely independent, do not affect each other

  5. Can not copy, to learn for use, deep and shallow copy specific use needs to be combined with the specific situation

At the end

Writing is not easy, welcome everyone to like, comment, your attention, like is my unremitting power, thank you to see here! Peace and Love.