Reputation: 889
I have this code:
let a = {x: "x"};
let b = {b: "b"};
let versions = [a, b];
let copyOfVersions = Array.from(versions);
let test = ["test"];
copyOfVersions[0].versions = Array.from(test);
console.log(versions[0].versions);
How come that versions
table values have changed too?
Thanks!
Upvotes: 0
Views: 62
Reputation: 7480
a
and b
are references to the objects {x: "x"}
and {b: "b"}
respectively.
When you create a new array, those references are copied to the new array but the referenced objects are NOT copied, it's still the original objects that are referenced.
copyOfVersions[0]
gets the referenced object, the same object referenced by versions[0]
, and then you create the property versions
on that object. Since the object itself was never copied, you're modifying the original object.
Upvotes: 1
Reputation: 448
Yes, you created a new instance of an array by using Array.from. So versions and copyOfVersions are two different objects, but they both contain list of references to the same objects. So that means when you say copyOfVersions[0] and versions[0] you are basically accessing the same object a. Then when you use .versions you are adding a new field. In the end, only object a has been changed and that's what you see as print out.
Upvotes: 1