一、浅拷贝的实现方法
1.Object.assign方法
let obj1={
name:"aaa",
}
let obj2={
age:20
}
let obj3=Object.assign(obj1,obj2)
// obj3.age=30
console.log(obj1);
console.log(obj3);
console.log(obj1==obj3);
console.log(obj1===obj3);
结果为:
2.直接赋值
let obj1={
name:"aaa",
age:20,
hobby:{
life:"eat"
}
}
let obj2=obj1
obj2.name="hhh"
console.log(obj1);
console.log(obj2);
console.log(obj1==obj2);
console.log(obj1===obj2);
二、深拷贝的实现方法
1.递归
let obj1={
name:"aaa",
age:20,
hobby:["1","2","3"]
}
function deepClone(obj){
if(obj===null ||typeof obj!=="object"){
return obj
}
let obj2
if(obj&&typeof obj==="object"){
obj2={}
for(let key in obj){
if(obj.hasOwnProperty(key)){
obj2[key]=deepClone(obj[key])
}
}
}
if(Array.isArray(obj)){
obj2=[]
for(let i in obj){
obj2.push(deepClone(obj[i]))
}
}
return obj2
}
let obj3=deepClone(obj1)
// obj3.hobby[1]=5
console.log(obj3);
console.log(obj1);
console.log(obj1==obj3);
console.log(obj1===obj3);
输出结果为:
2.json
let obj1={
name:"aaa",
age:20,
hobby:["1","2","3"]
}
let obj2=JSON.parse(JSON.stringify(obj1))
obj2.hobby[2]="45"
console.log(obj2);
console.log(obj1);
console.log(obj1==obj2);
console.log(obj1===obj2);
输出结果为:
文章来源:https://www.toymoban.com/news/detail-646919.html
文章来源地址https://www.toymoban.com/news/detail-646919.html
到了这里,关于如何实现浅拷贝和深拷贝的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!