[TypeScript] Shallow copy object by using spread opreator
2024-09-03 20:37:30
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
最新文章
- mvc SelectList selected失效的解决方法
- position之fixed固定定位、absolute绝对定位和relative相对定位
- Objective-C 中类属性(修饰)
- C#装箱和拆箱(值类型和引用类型之间的转换)
- javascript对象与实例
- C# 中的值类型和引用类型
- 超强vim配置文件
- js获取每个按键的ASCII值
- Linux 下安装python软件包
- Why is celsius = 5 * (fahr - 32) / 9 ?
- iOS开发播放文本
- Django models Fild详解
- 一个普通的 Zepto 源码分析(三) - event 模块
- 201521123018 《Java程序设计》第3周学习总结
- SSH反向连接及Autossh
- (转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS
- oracle故障解决
- Android逆向 破解第一个Android程序
- Redis存读取数据
- linux中tomcat内存溢出解决办法