related codes
var des = 1;
var obj = {b: 2};
for(var key in obj) {
console.log(des, key); // 1, "b"
des[key] = obj[key]; // ???
console.log(des[key]); // undefined
}
question
How to execute the sentencedes [key] = obj [key]? The code does not report an error, but the des [key] print result is undefined
Code source
function deepCopy(des, src) {
if(!src || typeof src !== "object") {
return des;
}
for (var key in src) {
let obj = src[key];
if(obj && typeof obj === "object") {
des[key] = des[key] || {};
deepCopy(des[key], obj);
} else {
des[key] = src[key];
}
}
return des;
}
console.log(deepCopy({a: 1}, {a: {b: 2}})); // {a: 1}
console.log(deepCopy({a: {}}, {a: {b: 2}})); // {a: {b: 2}}