Depth copy
-
What are deep and shallow copies? What’s the difference between shallow copy and assignment?
Shallow copy: Creates a new object that copies the first reference of the original object. That is, when the attribute value of the original object is the basic data type, the value is directly copied. When the property value of the original object is an object, the pointer to the object is copied as the property value.
Therefore, if an object changes an attribute value whose type is a reference value after copying, the original object will be affected.
The difference between shallow copy and assignment is that assignment to an object does not create a new object. The rules are the same as variable copy. Deep copy:Create a new object and make a full copy of the original object out of memory. The copied object does not affect the original object.
-
How to implement shallow copy?
-
Object.assign()
Object.assign() copies the enumerable property values of any number of source objects to the target Object and returns the copied target Object.
This works like the following code:
function shallowCopy(target, source) { for (let key in source) { target[key] = source[key]; } return target; } Copy the code
-
Extended operator
When shallow copy is implemented with extended operators, the enumerable property values of a parameter object can be taken and copied to the target object.
let source = {}; let target = {... source};Copy the code
-
Array methods: array.slice () and array.concat ()
When slice() and concat() are called without arguments, they are equivalent to making a shallow copy of the array.
-
-
How to implement deep copy?
-
JSON.parse(JSON.stringify(obj))
Deep copy can be implemented using JSON methods, but JSON does not support all types of JavaScript, nor does it solve the problem of circular references.
-
Implement the deep-copy method yourself
function deepCopy(source, map = new WeakMap()) { // 1. If (source instanceof Object) {// 2. If (map.has(source)) return map.get(source); if (map.has(source)) return map.get(source); else if (source instanceof Array) { target = []; } else if (source instanceof Function) { return function () { return source.apply(this, arguments) }; } else if (source instanceof RegExp) {return new RegExp(source.source, source.flags); } else if (source instanceof Date) { return new Date(source); } else {target = {} // Save the traversed attribute object map.set(source, target) with map; for (let key in source) { target[key] = deepCopy(source[key], map); } } return target; } else return source; }Copy the code
-