天天看點

[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

繼續閱讀