The difference and method between js shallow copy and deep copy

In JavaScript, there are two ways to copy an object: shallow copy and deep copy. The difference between them is that the copied object has a different relationship with the original object.

Shallow copy creates a new object, but some properties of the new object and the original object point to the same memory address. That is, some properties in the new object are just references to properties of the original object. Modifying these properties in the new object will also affect the original object, since they point to the same memory. Common shallow copy methods include:

扩展运算符(Spread Operator):{...obj}
Object.assign() 方法:Object.assign({}, obj)
Array.prototype.slice() 方法(对于数组):arr.slice()

A deep copy is to completely copy an object, including the object's attribute values, rather than just copying the reference to the attribute. In this way, any modifications made on the new object will not affect the original object. Common deep copy methods include:

JSON.parse(JSON.stringify()) 方法:JSON.parse(JSON.stringify(obj))
注意:该方法可以实现深拷贝,但有一些限制,例如无法拷贝函数、正则表达式、循环引用等。

递归方法:自定义递归函数来遍历对象的属性,并进行深拷贝。

Guess you like

Origin blog.csdn.net/qq_44063746/article/details/130702488