封装一个深拷贝的函数
function DeepCopy(newObj, oldObj) {
for(let key in oldObj) {
//判定属性值的类型
let item = oldObj[key]
if(item instanceof Array) { //如果属性值为数组
newObj[key] = []
DeepCopy(newObj[key], item)
} else if(item instanceof Object) { //属性值为对象
newObj[key] = {}
DeepCopy(newObj[key], item)
} else { //基本数据类型
newObj[key] = item
}
}
}
实例:
let old = {
name: 'james',
age: 35,
now: {
team: 'lakers'
},
play: ['骑士', '热火', '湖人']
}
let new1 = {}
DeepCopy(new1, old)
console.log(new1)
/* 打印出
>{name: "james", age: 35, now: {…}, play: Array(3)}
age: 35
name: "james"
now: {team: "lakers"}
play: (3) ["骑士", "热火", "湖人"]
__proto__: Object
*/