How to copy an object using JavaScript?

To copy an object, you can use several different methods. Three commonly used methods will be introduced below: shallow copy, deep copy and object spread operator.

  1. Shallow copy
    Shallow copy refers to creating a new object whose attribute values ​​are references to the original object's attributes. This means that if the original object's property was a reference type (such as an array or object), then the new object's property will reference the same memory address. If you modify the properties of the original object, the properties of the new object will also change.

Here's how to use shallow copy:

// 原始对象
const originalObject = {
   
    
     name: 'John', age: 30 };

// 使用浅拷贝创建新对象
const copiedOb

Guess you like

Origin blog.csdn.net/Book_Sea/article/details/133487853