简体   繁体   中英

Shallow copy vs deep copy in array containing objects

Shallow copy is nothing but when trying to copy and change the contents of copied array {array containing objects and not primitive data types} the contents of the original array also got changed.

In the following case, why the dst[0]= {name: "tom"} is a deep copy and not a shallow copy (the contents of the original array "src" is not changed). On the contrary, the second operation which is dst[0].name= "tom" is creating a shallow copy as expected and changing the contents of src. Can someone please clarify this?

 let src = [{ name: 'brat' }, { age: 40 }] let dst = [...src] // dst[0]={name:"tom"} dst[0].name = "tom"; console.log(`src ${JSON.stringify(src)}`) console.log(`dst ${JSON.stringify(dst)}`)

That is because in the below line, you are not changing the copied property of src, instead you are re-assigning both 'key' and 'value' and replacing the old property altogether with a new property.

dst[0]={name:"tom"} 

is the same as doing this:

dst[0]={newName:"tom"} 

It's considered as dst's new property instead of the one copied from src, and that is the reason the original object does not change, because this 'name' property is not the same one that was copied from the original object.

When you use the {name: "tom" } to re-assign the value to dst, then dst[0] 's memory is released from the heap and a new object replaces dst[0] altogether, it is not the same object that was shallow copied from src[0] .

dst[0]={name:"tom"} and dst[0].name = "tom"; are not copies, they're just assignments. One changes the dst array (sets a new object as the first element), the other changes the first object (sets a new string for the .name property).

The shallow copy happens in the line let dst = [...src] , and if you're not changing that it's always a shallow copy where dst contains the same mutable objects as src .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM