[TypeScript] Shallow copy object by using spread opreator

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Shallow copy object by using spread opreator相关的知识,希望对你有一定的参考价值。

For example we have an object:

const todo = {
  text: "Water the flowers",
  completed: false,
  tags: ["garden"]
};

 

We shallow copy it:

const shallowCopy = { ...todo };

 

Verify that shallowCopy is not todo:

console.log(todo === shallowCopy) // false

 

Change text prop of shallowCopy to somethingelse:

shallowCopy.text = "Mow the lawn"; 

console.log(shallowCopy.text) //  "Mow the lawn";
console.log(todo.text); // "Water the flowers"

 

But if we want to push a new value to the tags array:

shallowCopy.tags.push("weekend");

Then we can find out that, both shallowCopy and todo object\'s tags both changed.

The reason for that is the shallow copy\'s array prop, still point to the original reference. We need to do a deep clone in order to avoid the mistake.

[Javascript] Different ways to create an new array/object based on existing array/object

以上是关于[TypeScript] Shallow copy object by using spread opreator的主要内容,如果未能解决你的问题,请参考以下文章

python中的shallow copy 与 deep copy

deep copy and shallow copy

Python 深浅拷贝 (Shallow copy and Deep copy in Python)

Python - 拷贝 - 浅拷贝(Shallow Copy)和深拷贝(Deep Copy)

Python (zip, lambda, map, shallow copy, deepcopy)

Python copy模块