[JS] The difference and implementation method of medium-deep copy and shallow copy

1. Concept

  1. Assignment is not copying
  2. JS's deep copy and shallow copy mainly work in multi-layer arrays or objects, among which:

Shallow copy:

Only the first-level array or object is copied, and other layers copy the original stored memory address (modifying other deep levels will affect the original object)

Deep copy:

Construct a new composite array or object. Each level opens up a new space in the heap memory and has no influence on the original array or object.

2. Implementation method

How to implement shallow copy:

  1. For objects: use Object.assign()method, for example: let newObj = Object.assign({}, oldObj);
  2. For arrays or objects: use the spread operator ( ...) for shallow copying, for example: let newObj = {…oldObj}; let newArr = […oldArr];
  3. For arrays: Use slice()the method of the array to make a shallow copy, for example: let newArray = oldArray.slice()

How to implement deep copy

  1. JSON.parse(JSON.stringfy(obj))
    JSON.parse(JSON.stringify(obj)): Serialize the object into a JSON string, and then parse the string into a new object. This method can achieve deep copy, but it has some limitations, such as the inability to copy functions, circular references and other non-serializable properties;
  2. 手动递归拷贝:
    Use recursive method to traverse the properties of the object and copy them to the new object one by one. This method can achieve deep copy, but it requires manual writing of code and is not suitable for objects with deep nesting levels.
// 递归实现深拷贝
function deepClone(obj) {
    
    
 if (typeof obj !== 'object' || obj === null) {
    
    
   return obj;
 }
 let newObj = Array.isArray(obj) ? [] : {
    
    };
 for (let key in obj) {
    
    
   newObj[key] = deepClone(obj[key]);
 }
 return newObj;
}
  1. Lodash 的 _.cloneDeep()(Using third-party libraries)
    Deep copy can be implemented, and special attributes such as copy functions and circular references are supported, making it easy to use;

おすすめ

転載: blog.csdn.net/sunshineTing2/article/details/131941961