码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Shallow copy object by using spread opreator

时间:2017-11-13 19:47:53      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:hal   div   different   array   col   ase   pre   color   http   

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

标签:hal   div   different   array   col   ase   pre   color   http   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!