为什么此代码引用了不同的结果 [英] Why this code references different result

查看:39
本文介绍了为什么此代码引用了不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS新手,正在学习JS中的值和引用类型,但是在以下代码上我遇到了一些困惑:

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

上面的代码输出17,但是为什么呢?好吧,arr是一个引用类型,也就是说,它是可变的,因此我们将obj.arr均衡为变量z,以便z保留对obj对象中arr数组的引用.最后,z保持为17,然后将其更改为25,但输出为17.

The above code outputs 17 but why? Well, arr is a reference type, that is, it is mutable then we equalize obj.arr to variable z so z holds reference to arr array in obj object. Finally, z holding 17 then we change it to 25 but it output 17.

推荐答案

第一次,您会遇到类似的事情:

First time, you have something like this:

obj ---> {
           arr ---+
         }        |
                  |
                  v
                  [
                     [0] ---+
                  ]         |
                  ^         |
                  |         v
                  |         { x: 17 }
                  |
                  |
z ----------------+

请注意, z 现在指向 obj.arr 相同的对象,但 不是 obj.arr .

Note that z now points the same object as obj.arr but not obj.arr.

现在修改 z 的值将导致 z 的值(和引用)被更改,但是 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 }
        ]

这就是 obj.arr 不变的原因.

但是如何通过 z 进行更改?

But how to change it via z?

您无法更改 obj.arr 本身,但仍可以对其进行变异.

You can't change obj.arr itself, but you can still mutate it.

使用以下代码代替您的代码:

Instead of your code, use this:

z[0] = { x:25 }

现在您拥有:

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

这篇关于为什么此代码引用了不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆