手搓深拷贝
const obj = {
name: "tom",
age: 19,
hobby: ["篮球", "排球"],
sayhi() {
console.log("sayhi");
},
info:{
name:'jerry',
age: 20
}
};
const o = {};
//在写Object和Array的判断条件时,数组必须写在对象的前面。因为数组也是一种对象
function fn(newObj, oldObj) {
for (const key in oldObj) {
if (!newObj[key]) {
// Array
if (oldObj[key] instanceof Array) {
newObj[key] = []
fn(newObj[key], oldObj[key]);
}
// Object
else if(oldObj[key] instanceof Object) {
newObj[key] = {}
fn(newObj[key], oldObj[key]);
}
else {
newObj[key] = oldObj[key];
}
}
}
}
fn(o, obj);
o.hobby[0] = '乒乓球'
o.info.age = '22'
console.log(o);
/*{
name: 'tom',
age: 19,
hobby: [ '乒乓球', '排球' ],
sayhi: {},
info: { name: 'jerry', age: '22' }
}*/
console.log(obj);
/*{
name: 'tom',
age: 19,
hobby: [ '篮球', '排球' ],
sayhi: [Function: sayhi],
info: { name: 'jerry', age: 20 }
}*/
标签:name,oldObj,age,newObj,key,拷贝,sayhi
From: https://www.cnblogs.com/doud/p/17582297.html