Make a summary every day, persistence is victory!

/** @date 2021-06-13 @description Deep copy */Copy the code

One (sequence)

Shallow copy and deep copy:

In js, if the reference data type (obj) refers to another reference (childObj), the shallow copy will only copy the childObj’s reference address, that is, if the value of the childObj is changed, The childObj in the new copy object will also change; In deep copy, all values are copied. Even if the data type is referenced, a new object will be declared. Data in the original data will not be changed and the data will not be copied.

Ii (Code implementation)

Const isObject = (target) => {return typeof target === "object" && target! == null; }; // Const cloneDeep = (target, hash = new WeakMap()) => { isObject(target)) { return target; If (hash.has(target)) {return hash.get(target); if (hash.has(target)) {return hash. } // Define the copied object const cloneTarget = array.isarray (target)? [] : {}; // Insert the value hash.set(target, cloneTarget) into the hashMap; / / processing symbol is const symKeys = Object. GetOwnPropertySymbols (target); symKeys.forEach((item) => { const symTarget = target[item]; if (isObject(symTarget)) { cloneTarget[item] = cloneDeep(symTarget, hash); } else { cloneTarget[item] = symTarget; }}); // non-symbol const keys = object.keys (target); keys.forEach((key) => { const objTarget = target[key]; if (isObject(objTarget)) { cloneTarget[key] = cloneDeep(objTarget, hash); } else { cloneTarget[key] = objTarget; }}); return cloneTarget; }; // test const childObj = {c: 3}; const obj = { a: 1, b: 2, childObj }; obj.childObj = obj; const sym = Symbol("test"); obj[sym] = 3; console.log(obj); // {a: 1, b: 2, childObj: {... }, Symbol(test): 3} const newObj = cloneDeep(obj); console.log(newObj); // {a: 1, b: 2, childObj: {... }, Symbol(test): 3} obj.a = 4; obj[sym] = 5; console.log(obj); // {a: 4, b: 2, childObj: {... }, Symbol(test): 5} console.log(newObj); // {a: 1, b: 2, childObj: {... }, Symbol(test): 3} const arr = [1, 2, {a: 3}]; const newArr = cloneDeep(arr); console.log(arr); // [1 ,2 ,{a: 3}] console.log(newArr); // [1 ,2 ,{a: 3}] arr[0] = 4; arr[2].a = 5; console.log(arr); // [4 ,2 ,{a: 5}] console.log(newArr); // [1 ,2 ,{a: 3}]Copy the code

Three (Conclusion)

Everyone healthy Dragon Boat Festival!