一.浅拷贝
对象的浅拷贝
- Object.assign(newval,oldval)
const old={
name:'乔治'
}
const newo = {}
Object.assign(newo,old)
newo.name='佩奇'
console.log(newo,old)
//newo={name:'佩奇'}
//old={name:'乔治'}
2.扩展运算符 ...
const old={
name:'乔治'
}
const newo = {...old}
newo.name='佩奇'
console.log(newo,old)
//newo={name:'佩奇'}
//old={name:'乔治'}
数组的浅拷贝
1.扩展运算符 ...
const old=[1,2,3]
const newo = [...old]
newo[0]='佩奇'
console.log(newo,old)
//newo=[1,2,3]
//old=['佩奇',2,3]
2.Array.prototype.concat.apply() 了解
二.深拷贝
递归
const old ={
name:'佩奇',
address:{
where:'中国'
}
}
function deepClone(old){
const newObj =Array.isArray(old) ? [] : {};
for(let key in old){
if(typeof(old[key]) === 'object'){
newObj[key]=deepClone(old[key])
}else{
newObj[key]=old[key]
}
}
return newObj
}
const newObj=deepClone(old)
newObj.address.where='美国'
console.log(old,newObj)
JSON
const old ={
name:'佩奇',
address:{
where:'中国'
},
num:[1,2,3]
}
const newObj =JSON.parse(JSON.stringify(old))
newObj.address.where='美国'
newObj.num[0]='666'
console.log(old,newObj)
第三方库 lodash里面的 cloneDeep方法
先下载lodash.js
然后引入<script src="lodash.js"></script>
然后使用
const old ={
name:'佩奇',
address:{
where:'中国'
},
num:[1,2,3]
}
const newObj=_.cloneDeep(old)
newObj.address.where='美国'
newObj.num[0]='666'
console.log(old,newObj)
三.总结
深浅拷贝都是针对引用数据类型来说的。浅拷贝是只拷贝了一层,如果引用数据类型里面还有引用数据类型,拷贝的是一个地址。深拷贝就是一个全新的数据了,有自己独立的空间。
const a ={
age : 18,
where:{
address:'北京'
}
}
const b= {...a}
b.age = 19
console.log(a.age); //18
console.log(b.age); //19
b.where.address = '武汉'
console.log(a.where.address); //'武汉'
console.log(b.where.address); //'武汉'