深拷贝和浅拷贝,简单说:
就是假设B复制了A,当修改A时,看B是否会发生变化,如果B跟着变了,就是浅拷贝,没有就是深拷贝
1.通过遍历赋值
浅拷贝
let obj = {
a : 'hellow',
b:{
a:'javascript',
b:365
},
c:[12,23,'数组']
}
function simpluabfdj(newobj){
let obj = {}
for(let i in newobj){
obj[i] = newobj[i]
}
return obj
}
let objCopy = simpluabfdj(obj)
console.log(obj);
console.log(objCopy);
深拷贝
let obj = {
a : 'hellow',
b:{
a:'javascript',
b:365
},
c:[12,23,'数组']
}
function deepClone(startObj,endObj){
let obj = endObj || {}
for(let i in startObj){
if(typeof startObj[i] === 'object'){
obj[i] = startObj[i].constructor === Array?[]:{}
deepClone(startObj[i],obj[i])
}else{
obj[i] = startObj[i]
}
}
return obj
}
let objCopy = deepClone(obj)
objCopy.b.a = 'word1'
console.log(obj);
console.log(objCopy);
2.通过Object.create()
浅拷贝
let obj = {
a : 'hellow',
b:{
a:'javascript',
b:365
},
c:[12,23,'数组']
}
let objCopy = Object.create(obj)
console.log(obj);
console.log(objCopy);
3.通过JSON.parse()和JSON.stringify()
深拷贝,,最常用的
let obj = {
a : 'hellow',
b:{
a:'javascript',
b:365
},
c:[12,23,'数组']
}
let objCopy = JSON.parse(JSON.stringify(obj))
objCopy.b.a = 'word1'
console.log(obj);
console.log(objCopy);