浅拷贝和深拷贝
浅拷贝
Object.assign(target,…sources)
<script>
var obj = {
id: 1,
name: 'Tom',
msg: {
age: 18
}
}
var ob = {}
for(var k in obj){
ob[k] = obj[k]
}
console.log(ob)
ob.msg.age = 20;
console.log(obj)
Object.assign(ob,obj)
</script>
深拷贝
<script>
var obj = {
id: 1,
name: 'Tom',
msg: {
message: '错误'
},
color: ['pink','aqua']
}
var ob = {}
function deepCopy(newObj,oldObj){
for(var k in oldObj){
var item = oldObj[k]
if(item instanceof Array){
newObj[k] = []
deepCopy(newObj[k],item)
}else if(item instanceof Object){
newObj[k] = {}
deepCopy(newObj[k],item)
}else{
newObj[k] = item
}
}
}
deepCopy(ob,obj)
console.log(ob);
ob.color.push('red')
console.log(obj)
</script>