One. 浅拷贝:
一、理解
1)对象的逐位复制
2)只复制指向某个对象的指针,而不是复制对象本身,新旧对象还是共享同一块内存
3)修改对象A的属性,另一个对象B的属性《会》被影响改变
二、执行
1-1 Object.assign()
方法可以把任意多个的源对象自身的可枚举属性拷贝给目标对象,然后返回目标对象。 注意:当object只有一层的时候,是深拷贝。
var obj = {
a: {
name: 'zhuxubin',
age: 18,
reg: /^1[3-9]\d{10}$/,
test: undefined
}
}
var newObj = Object.assign({}, obj)
console.log(newObj)
效果:
1-2 直接赋值
const name = 'zhuxubin'
const newName = name
console.log(newName)
效果:
1-3 ... 扩展运算符是ES6新增加的内容
三、弊端(常用)
改变一个值的属性 也会 影响 另一个值的属性
Two. 深拷贝:
一、理解
1)新建一个对象,再进行逐位复制
2)会开辟新的栈,两个对象是不同的地址
3)修改对象A的属性,另一个对象B的属性《不会》被影响改变
二、执行
1-1 JSON.prase(JSON.stringify())
//封装 深拷贝函数 JSON.parse(JSON.stringify(拷贝对象))
const deepClone = (obj) => {
return JSON.parse(JSON.stringify(obj))
}
const obj = {
a: {
b: {
name: 'zhuxubin'
}
},
reg: /^1[3-9]\d{10}$/, // 正则
sex: undefined, // undefined
cloneFn: (sex) => console.log(sex) //匿名函数
}
const newObj = deepClone1(obj)
console.log(newObj)
效果:
1-2 structuredClone
const obj = {
a: {
b: {
name: 'zhuxubin'
}
},
reg: /^1[3-9]\d{10}$/, // 正则
sex: undefined // undefined
}
const newObj = structuredClone(obj)
console.log(newObj)
效果:
1-3 函数库lodash等 我建议使用1-2
1-4 封装深拷贝函数
function deepClone(obj){
let newObj = {};
for(let key in obj){
if(typeof obj[key] === 'object'){
newObj[key] = deepClone(obj[key])
}else{
newObj[key] = obj[key]
}
}
return newObj;
}
三、弊端(常用)
1) JSON.parse(JSON.stringify())
它不能拷贝到 1.函数、2.正则表达式、3.未定义的值、4.功能、5.dom元素、6.ETC
2)structuredClone
它不能拷贝到 1.函数、2.功能、3.dom元素、4.ETC
3)函数库lodash等
不如structuredClone方法