How to implement deep copy: 1. Use the "Object.assign({},obj)" statement to implement; 2. Use the "JSON.parse(JSON.stringify(obj))" statement to implement; 3. Use the "$.extend(true,[],arr)" statement to achieve this.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
What is deep copy
Deep copy is relative to shallow copy. The main difference is reflected in the reference type. Essentially, a shallow copy simply copies the reference address in the stack, so when you modify the newly copied value, the copied object will also be modified by you; while a deep copy will Create space for new objects in heap memory, so the copied objects will not be modified for no reason.
How to implement deep copy in es6
Method 1: Use Object.assign
Object.assign performs a deep copy of the object by default, but what we need to note is that it only performs a deep copy of the outermost layer. That is, when there are objects nested within the object, it will be nested. The object is still shallow copied;
function cloneDeepAssign(obj){ return Object.assign({},obj) }
(warm reminder: in the array copy method, use ...
, slice
, concat
The same effect is achieved when copying, only the outermost layer is copied deeply)
At the same time, we know that Object.assign
is aimed at the enumerable properties of the object itself, and for the non-enumerable properties No effect;
So, when we deal with a single object at a level, we can consider this method, which is simple and fast. (I tried it, but it doesn’t support undefined)
Method 2: Use JSON
This is the one we most often mention This is a deep copy method. Generally, most deep copies can be solved using JSON. The essence is that JSON will build new memory by itself to store new objects.
function cloneDeepJson(obj){ return JSON.parse(JSON.stringify(obj)) }
But what we need to pay attention to is:
will ignore undefined
and symbol
;
cannot be copied to Function
because the JSON
format string does not support Function
and will be automatically deleted during serialization;
Such as Map
, Set
, RegExp
, Date
, ArrayBuffer
and other built-in types will be lost during serialization;
does not support copying of circular reference objects; (circular references can be roughly understood as a certain attribute in an object The value is itself)
Method 3: Using jQuery’s $.extend()
var array = [1,2,3,4]; var newArray = $.extend(true,[],array);
Obviously, the maximum The disadvantage is that we also need to introduce the jQuery library, so it is not commonly used;
[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of What are the several implementation methods of es6 deep copy?. For more information, please follow other related articles on the PHP Chinese website!