为什么 javascript 对象值会发生变化? [英] Why javascript object value is changed?

查看:50
本文介绍了为什么 javascript 对象值会发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释为什么输出值改为20, 2"而不是原来的1, 2"?

Can anyone explain to me why the output value is changed to "20, 2" instead of the original "1, 2"?

<!DOCTYPE html>
<html>
<body>
  <p id="demo"></p>
  <p id="demo1"></p>
  <script>
    var x = {
      a: 1,
      b: 2
    };
    var y = x;
    y.a = 20;
    document.getElementById("demo").innerHTML = x.a;
    document.getElementById("demo1").innerHTML = x.b;
  </script>
</body>
</html>

推荐答案

您将 y 指向 x 的引用,而 x 本身指向对象 {a:1,b:2}.

You are pointing y to the reference of x which itself is pointing to the object {a:1,b:2}.

所以在内存中是:

x --> {a:1,b:2}

执行y = x后,它变成:

y --> x --> {a:1,b:2}

或者简单地说:

x --> {a:20,b:2}
         ^
         |
y -------

现在当你做 ya = 20 时,因为 yx 在对象的属性改变时都指向同一个对象通过引用 xy 中的任何一个,更改将反映在两个引用中:

Now when you do y.a = 20, since y and x are both pointing to the same object when properties of the object is changed through either of the references x or y the change will be reflected in both the references:

y --> {a:20,b:2}
        ^
        |
x -------

这就是为什么当你得到 x.a 时你会得到 20,2.

That is why you get 20,2 when you get x.a.

这篇关于为什么 javascript 对象值会发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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