Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to JS and was learning value and reference types in JS but I faced some confusion on the below code:

const obj = {
  arr: [{
    x: 17
  }]
};

let z = obj.arr;

z = [{
  x: 25
}];

console.log(obj.arr[0].x);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...