Analysis of the difference between deep copy and shallow copy source code

problem description

the difference between the two is that one creates a new memory space, and the other is just a reference relationship, but I want to know why the difference in the source code leads to the difference between deep copy and shallow copy

related codes

this.dataInfo = JSON.parse(JSON.stringify(data[0][0]));
this.dataInfo = data[0][0];

what result do you expect? What is the error message actually seen?

Oct.27,2021

if it is a shallow copy, the values of the two will affect each other, while the deep copy will not

data[0][0]={a:1}
this.dataInfo = JSON.parse(JSON.stringify(data[0][0]));
data[0][0]={a:2}
console.log(this.dataInfo) // {a:1}
this.dataInfo={a:3}
console.log(data[0][0]) // {a:2}
data[0][0]={a:1}
this.dataInfo = data[0][0];
data[0][0]={a:2}
console.log(this.dataInfo) // {a:2}
this.dataInfo={a:3}
console.log(data[0][0]) // {a:3}

The

shallow copy just creates a new alias to refer to the memory area.

Deep copy reopens a memory area and copies in the value of the previous memory area, so that the initial values of the two memory areas are the same, but the next operation does not affect each other.

Menu