es6 deconstruction is not a deep copy. If the original object of deconstruction is a one-dimensional array or object, then destructuring is a deep copy. If the original object of deconstruction is a multi-dimensional array or object, then destructuring is a shallow copy. Because destructuring cannot achieve the effect of deep copy for multi-dimensional arrays, destructuring cannot It is considered a deep copy, but should be a shallow copy.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
Everyone must be familiar with the knowledge about destructuring assignment in ES6. The so-called destructuring assignment is a solution that uses a pattern to quickly retrieve data from the target structure, for example:
Through destructuring, we can easily retrieve the data we want from arrays and objects. . However, you may ask, what does this have to do with deep copy and shallow copy?
Let’s first review the deep copy and shallow copy.
The so-called shallow copy and deep copy: Shallow copy means that during the copy process, the part during traversal is of object/array type Points to the original address, while deep copy completely opens up a new memory address. In other words,
So, in deconstruction, is it a deep copy or a shallow copy?
In the above code, we deconstruct the array and object respectively, then modify the value of the destructured variable, and then print the variable and the original array and object respectively. The results are as follows:
We found that the data of the original array and object have not changed. Does this mean that the destructuring assignment is a deep copy? ?
Let’s slightly modify the example, the code is as follows:
We added a new data attribute to the object, the data of data is an array, and then after destructuring, we The data of data was modified, and the result is as follows:
We found that the change of the deconstructed variable data caused the change of the original data, that is, the destructured assignment is still a shallow copy.
To summarize:
Destructuring assignment, if the original object being deconstructed is a one-dimensional array or object, its essence is to perform an equal sign assignment on the basic data type, then it is a deep Copy;
If it is a multi-dimensional array or object, its essence is to assign equal signs to reference type data, then it is a shallow copy;
The final conclusion is: destructuring assignment is a shallow copy (because it cannot do multi-dimensional Array or object achieves the function of deep copy);
[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of Is es6 deconstruction a deep copy?. For more information, please follow other related articles on the PHP Chinese website!