Why this code references different result

后端 未结 4 1369
眼角桃花
眼角桃花 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);
    

提交回复
热议问题