首页 > 其他 > 详细

[TypeScript] Shallow copy object by using spread opreator

时间:2017-11-13 18:55:41      阅读:171      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Answer1215/p/7827457.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!