Whether the copy of the object by the spread operator is a deep copy or a shallow copy

The spread operator performs a shallow copy

When you copy an object using the spread operator, it creates a new object and copies the properties and values ​​of the original object into the new object. If the original object contained other objects as its property values, then the new object and the original object share those properties, and they both point to the same object.

for example

const obj1 = {
    
    
  name: 'maomao',
  info: {
    
    
    age: 18
  }
}
const obj2 = {
    
    ...obj1}
obj2.name = 'ayetongzhi'
obj2.info.age = 22
console.log('obj1', obj1)
obj1 {
    
     
  name: 'maomao',
  info: {
    
     age: 22 }
}
console.log('obj2', obj2)
obj2 {
    
    
  name: 'ayetongzhi',
  info: {
    
     age: 22 }
}

In the above example, we define an object obj1, and use the spread operator to copy obj1 to the variable obj2.
Then obj2 modifies the name attribute and the age attribute in the info reference object.
After printing the results, we found that the value of the info reference object of obj1 has also changed.
Therefore, we can know that the spread operator performs a shallow copy.

Guess you like

Origin blog.csdn.net/qq_42816270/article/details/129351962