3 ms·
It doesn't do anything and was my attempt to give a simple example that is somewhat obvious while glossing over the complexity let arr = [{a: 1, b: ["a", "
by wongarsu 7y ago
It doesn't do anything and was my attempt to give a simple example that is somewhat obvious while glossing over the complexity
let arr = [{a: 1, b: ["a", "b"]}, {a: 9, b: ["a","c"]}];
let b = "!"
for(let e of arr) e = b;
console.log(arr)
[{a: 1, b: ["a", "b"]}, {a: 9, b: ["a","c"]}] (unmodified)
for(let e of arr) e.a = 2;
console.log(arr)
[{a: 2, b: ["a", "b"]}, {a: 2, b: ["a","c"]}] (modified)
for(let e of arr) {let copy = {...e}; copy.a = 4;}
console.log(arr)
[{a: 2, b: ["a", "b"]}, {a: 2, b: ["a","c"]}] (unmodified)
for(let e of arr) {let copy = {...e}; copy.b[0] = "!";}
console.log(arr)
[{a: 2, b: ["!", "b"]}, {a: 2, b: ["!","c"]}] (modified)
The most frustrating thing about all of this is that the best way to make a deep copy to avoid all unwanted modification is JSON.parse(JSON.stringify(arr))
- Izkata 7y ago...honestly, I don't see much complexity here. Understanding of reference types and the difference between deep copy and shallow copy makes it pretty straightforward - the result is the same as it would be in python or java.
- wongarsu 7y agoI don't think Python or Java are examples of good or simple behavior here. Java at least has a strong culture of "copy everything or make it immutable at class boundaries" while javascript libraries often leave you guessing. Examples where this is easy are C where every copy and allocation is very explicit, C++ which has a good `const` concept that's actually useful, or Rust with it's ownership concept that makes mutability very obvious.
- jacobwilliamroy 7y agoThanks for sharing more context. I see what you were trying to illustrate with your earlier examples now. Why not make a little library so you can do these kinds of things safely without reimplementing them every project? Maybe call it safeCopy or something.