First time, you have something like this:
obj ---> {
arr ---+
} |
|
v
[
[0] ---+
] |
^ |
| v
| { x: 17 }
|
|
z ----------------+
Note that z
now points the same object as obj.arr
but not obj.arr
.
Modifying the value of z
now will result in the value (and the reference) of z
is changed, but obj.arr
refers to the same object as before:
obj ---> {
arr ---+
} |
|
v
[
[0] ---+
] |
|
v
{ x: 17 }
z ----> [
[0] ----> { x: 25 }
]
That's why obj.arr
didn't change.
But how to change it via z
?
You can't change obj.arr
itself, but you can still mutate it.
Instead of your code, use this:
z[0] = { x:25 }
Now you have:
obj ---> {
arr ---+
} |
|
v
[
[0] ---> { x: 25 }
]
^
|
| { x: 17 } -----> Garbage collection
|
|
z ----------------+
const obj = {
arr: [{ x: 17 }]
};
let z = obj.arr;
z[0] = { x: 25 };
console.log(obj.arr[0].x);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…