Why this code references different result

后端 未结 4 1360
眼角桃花
眼角桃花 2020-12-11 23:21

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

相关标签:
4条回答
  • 2020-12-11 23:33
    const obj = {
     arr: [{ x: 17 }]
    };
    
    /**
     * z -> it is only reference to original object (const obj in our case). 
     * It is like another door to the same room
     */
    let z = obj.arr;
    
    /*
     * now z -> points to other value (array), but previous still exist
     */
    z = [{ x: 25 }]; 
    
    console.log(obj.arr[0].x);
    
    0 讨论(0)
  • 2020-12-11 23:42

    The reference to obj.arr is replaced. z = [{ x: 25 }]; simply creates a new array with a new object, { x: 25 }, inside it. Then, it places a reference to this new array into z.

    0 讨论(0)
  • 2020-12-11 23:50

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

    0 讨论(0)
  • 2020-12-11 23:50

    You've just created z, which is a copy of obj.arr . If you change the value of z, the copy, the original (obj.arr) do not change.

    I'm French that's why my english isn't perfect

    0 讨论(0)
提交回复
热议问题