let obj = {
name: "张三",
age: 18
}
let user = obj
user.name = "李思"
console.log(obj);
console.log(user);
?
?
user和obj的地址是同一个,所以user修改了name的值也会影响obj的name值
浅拷贝
由此出现了浅拷贝:其作用就是用于解决数据共享的问题
方式1:合并对象,Object.assign({},对象),第一个参数必须是空对象,为了得到一个新的地址
let obj = {
name: "张三",
age: 12,
sex: "男"
}
let user = Object.assign({}, obj)
user.name = "李华"
console.log(obj);
console.log(user);
?
?
方式2:for...in遍历对象,?先声明一个空的对象,得到一个新的地址
let obj = {
name: "张三",
age: 12,
sex: "男"
}
let user = {}
for (const key in obj) {
user[key] = obj[key]
}
user.name = "李华"
console.log(obj);
console.log(user);
深拷贝
解决浅拷贝只能拷贝一层的问题
方式1:JSON的两个核心方法--可以解决95%的问题,例如undefined,null,NaN,Infinity函数等进行深拷贝都会导致内容丢失
let obj = {
name: "张三",
age: 12,
sex: "男",
likes: ["篮球", "睡觉"],
cuser: {
name: "张无忌",
job: "it"
}
}
let user = JSON.parse(JSON.stringify(obj))
user.cuser.job = "java"
user.likes.push("游戏")
user.name = "李华"
console.log(obj);
console.log(user);
方式2:Lodash解决方式1的解决不了的问题
<script src="./lodash.js"></script>
<script>
let obj = {
name: "张三",
age: 12,
sex: "男",
money: Infinity,
b: NaN,
likes: ["篮球", "睡觉"],
cuser: {
name: "张无忌",
job: "it"
}
}
let user = _.cloneDeep(obj)
user.cuser.job = "java"
user.likes.push("游戏")
user.name = "李华"
console.log(obj);
console.log(user);
</script>
|