Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - Why this code references different result

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...