Vue shallow copy deep copy

A simple summary of shallow copy and deep copy

Shallow copy only copies the pointer to an object, not the object itself. The old and new objects still share the same memory. However, deep copy will create an identical object. The new object does not share memory with the original object, and modifications to the new object will not change the original object.

Shallow copy

// 拷贝对象
{
    
    ..objValue}
// 拷贝数组
[...arrValue]

Deep copy 1 (not recommended)

// value为要拷贝对象
JSON.parse(JSON.stringify(value))

JSON.parse(JSON.stringify()) copies time objects, Error objects, regular expressions, functions, or undefined and other values. This method will cause problems.

  1. If there is a time object in json, the serialization result is: time object => string form
  2. If there are RegExp and Error objects in json, the serialization result will only get empty objects RegExp and Error => {}
  3. If there is function, undefined in json, the serialization result will lose function, undefined.
  4. If there are NaN, Infinity and -Infinity in json, the serialization result will become null
  5. If there is an object in json that is generated by a constructor, the serialization result will discard the constructor of the object.
  6. Deep copy cannot be implemented if there is a circular reference in the object.

deep copy 2

Using cloneDeep in Lodash

Official documentation

import {
    
     cloneDeep } from 'lodash-es'
// value为要拷贝对象
cloneDeep(value)

Guess you like

Origin blog.csdn.net/weixin_44872023/article/details/121762316