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}
des[key] = obj[key] 这句如何执行? 代码并没有报错, 但des[key]打印结果是undefined
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}}
呼如林
相关分类