javascript - 在 js 中复制对象(需要文档中的引用传递指导)

标签 javascript object cloning copying mutability

我查看了 js 文档,并在研究 object.assign() 中提到的文档时 如果源值是对对象的引用,则它仅复制引用值。

在我的下面的代码片段中,一个改变了原始对象,另一个则没有改变

    var objA = {
    a: 1,
    b: {
       c: 2,
       d: {
       e: 3,
     },
    },
  } 
var objC = { t: 1 };

  //why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC });  //this would add a prop to the objEmpty object

//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC);  //this will not
objC.a = 3;

console.log(objC);

console.log(objEmpty);

我通过尝试不同的场景来了解事情到底是如何工作的,我相信这与引用相关,但是如何?

文档中的另一个示例

  const obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```

why does js behave this way? why the 3 got changed but the other didn't?

Thanks in advance :)

最佳答案

why does js behave this way? why the 3 got changed but the other didn't?

因为Object.assign()实际上执行浅复制,所以您需要执行深复制

对对象进行深度复制。

方法有很多,最常见和流行的方法是使用 JSON.stringify()JSON.parse()

const oldObj = {a: {b: 1}, c: 2};
const newObj = JSON.parse(JSON.stringify(oldObj));
oldObj.a.b = 3; // will not affect the newObj
console.log('oldObj', oldObj);
console.log('newObj', newObj);

注意:有一个新的 JS 标准,名为 structured cloning 。它适用于所有浏览器:

method creates a deep clone of a given value using the structured clone algorithm.

const clone = structuredClone(object);

关于javascript - 在 js 中复制对象(需要文档中的引用传递指导),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73283123/

相关文章:

javascript - 使用 Enquire.js 根据媒体查询切换功能

javascript - 对单个文件的多个 HTTP 请求

javascript - 如何检查对象是否为空?

java - Wicket:克隆对象时出现内部错误

javascript - 将对象推送到数组中只返回最后推送的对象

javascript - 在 jQuery 中获取输入值

Java 字符串比较/引用

JavaScript 函数等效性

可克隆层次结构中的 C++ 复制构造函数和赋值

java - 在java中复制对象