两个相同的对象,当一个更改一个值时,另一个更改

时间:2020-07-08 16:22:35

标签: javascript

我有一个对象,然后将该对象复制到另一个变量中,当我更改对象的任何一个属性时,它将反映在另一个对象中。

(function() {
  let strA = {
    name: "John",
    age: "31",
    city: "New York"
  };
  let strB = strA;

  strA.name = "Ben";

  console.log(strA);
  console.log(strB);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

这是为什么,如何阻止它发生?

**编辑**

随着我对代码的深入研究,分配工作正常,直到我向其添加对象数组为止,如下所示

(function() {
  let strA = {
    name: "John",
    age: "31",
    city: "New York",
    stuff: [
        {color: "blue"},
        {color: "yellow"},
        {color: "red"}
    ]
  };
  let strB = Object.assign({}, strA);

  strB.name = "Ben";
  strB.stuff[0].color = "pink";
  
  console.log(strA);
  console.log(strB);
})();

这也改变了原始对象,我尝试了一下

(function() {
  let strA = {
    name: "John",
    age: "31",
    city: "New York",
    stuff: [
        {color: "blue"},
        {color: "yellow"},
        {color: "red"}
    ]
  };
  let strB = Object.assign({}, strA);
  strb.stuff = Object.assign({}, strA.stuff);
  
  strB.name = "Ben";
  strB.stuff[0].color = "pink";
  
  console.log(strA);
  console.log(strB);
})();

1 个答案:

答案 0 :(得分:3)

您没有复制对象。您正在引用它。它们是同一对象。您可以使用object.assign进行复制。

let strB = Object.assign({}, strA);