First, data types

Data types are divided into basic data types (String, Number, Boolean, Number, Null, Undefined, Symbol) and complex data types.

  1. Basic data types are characterized by data stored directly on the stack.

  2. Complex data types are characterized by the fact that the address (pointer) of the object is stored in the stack. The real data is stored in the heap memory, and the data in the pointed heap memory is retrieved by the pointer stored in the stack.

    The simple picture is as follows:

Shallow copy

Shallow copy: A shallow copy creates a new memory in the heap to hold the data of the original object. When the original object contains only the simple data type, the value of the primitive data type is copied, which gives the illusion that it is a deep copy. However, when there is a complex data type in the original object, only the pointer of the complex data type in the original object can be copied to point to the data in the space of the complex data type of the original object in the heap.

Summary: Shallow copy refers to copying only one level of objects, not multiple levels of objects.

Several ways to implement shallow copy (if missing, please add….)

Object.assign(
let obj = { person: { name: 'zs', age: 18 }, sports: 'soccer' }; let obj1 = Object.assign({}, obj); // console.log(obj1); obj1.person.age = 22; Obj1. sports = 'baseball'; // Deep copy console.log(obj);Copy the code

Running results:

Assign copies a multilevel complex data type using the object. assign method. Modify the sports attribute of the Object and the age attribute of the secondary Object using the copied Object.

2, expand the operator to achieve shallow copy
let obj = { person: { name: 'zs', age: 18 }, sports: 'soccer' }; let obj1 = { ... obj }; obj1.person.age = 22; Obj1. sports = 'baseball'; // deep copy console.log('obj1', obj);Copy the code

Running results:

The same result as the object. assign method can be clearly obtained by running the shallow copy method: Shallow copy can only implement deep copy of level-1 objects. If the original Object has complex data types, only address references of complex data types can be copied.

_. Clone method (lodash)

Next look at shallow copies of the two arrays

4, array.concat () method
let arr = [1, 3, { username: 'zs' }]; let arr1 = arr.concat(); arr1[0] = 2222; Arr1 [2]. Username = 'xiaoxiao '; console.log('arr', arr);Copy the code

Running results:

We can see that the array copy is the same as the above conclusion, I will not do more here.

5. Array.slice() method
let arr = [1, 3, { username: 'zs' }]; let arr1 = arr.slice(); arr1[0] = 2222; Arr1 [2]. Username = 'xiaoxiao '; console.log('arr', arr);Copy the code

Running results:

Shallow copy summary: after the above ‘Practice is the sole criterion for testing truth‘We can see thatShallow copy refers to copying only Pointers of complex data types when the original object has complex data types.

Deep copy

Deep copy: The deep copy is to copy all levels of the original object. No matter what data type exists in the original object, the data will be completely copied, put into a new space, and give new Pointers, and do not interfere with the original object.

Several ways to implement deep copy (if missing, please add….)

Parse (json.stringify ()
Let arr = [1, 3, {username: 'zs'}, function say() {console.log(' hello ');}]; let arr1 = JSON.parse(JSON.stringify(arr)); arr1[1] = 2222; Arr1 [2]. Username = 'xiaoxiao '; console.log(arr);Copy the code

Running results:

It can be clearly seen from the running result that the data is modified through the copied ARR1, and the data of the original object is not affected at all. However, it should be noted that the functions in the object disappear after the copy.

* * note: The ** json.parse (json.stringify ()) method, while it can implement deep copies of arrays or objects, cannot handle functions and regees because the resulting regees are no longer regees (empty objects) based on json.stringify and json.parse. The resulting function is no longer null.

CloneDeep (); cloneDeep (); cloneDeep (); Untalented and uneducated.. Must redouble your efforts!!
Extend ()
 var obj = {
            a: 1,
            b: {
                f: {
                    g: 1
                }
            },
            c: [1, 2, 3]
        };
        var obj1 = $.extend(true, {}, obj);
        console.log(obj.b.f === obj1.b.f); // false
Copy the code
4, handwritten recursive method to achieve deep copy

**** Recursive method to implement the principle of deep cloning: iterate through objects and arrays until they contain all basic data types, and then copy, that is, deep copy

Function deepCopy(obj) {let objClone = array.isarray (obj)? [] : {}; If (obj && typeof obj === 'object') {// Loop over object for (attr in obj) {// Determine if obj child is an object, if so, If (obj[attr] && Typeof obj[attr] === 'object') {objClone[attr] = deepCopy(obj[attr]); if (obj[attr] === 'object') {objClone[attr] = deepCopy(obj[attr]); } else { objClone[attr] = obj[attr]; }; }; }; return objClone; }; let a = [1, 2, [5, 7], 5]; b = deepCopy(a); b[1] = 2222; b[2][0] = 333; console.log(a); / / the sameCopy the code

Running results:

The above handwritten recursion method can achieve deep copy, but it is important to note that this is a simple implementation and not the best implementation.

End of speech!

A deep sea into the front, from now on the hair is passers-by, sister is also a passer-by…… We only keep learning specialized research can support the money….. hair transplant

Without further ado… In short: deep copy copies all levels of the original object, while shallow copy copies only one level!!

Among them, the final demonstration of the handwritten recursive method to achieve deep copy is just a simple function realization, not rigorous, only continuous study and study can make the code more rigorous, perfect, beautiful, amazing, admirable, make us proud. Life is more than learning……