Please tell me how to execute the following code

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 sentence

des [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}}
Jun.06,2022

Code source, des [key] = des [key] | | {};
des [key] is already an object and a reference type

in your own example, des is a non-reference type that cannot be directly [key]

friendly hint: there is a problem with this kind of clone from code source.
refer to https://codeshelper.com/a/11...


string is the original data type, and the js original data type is immutable. On the contrary, reference type data can be changed, such as object

.
Menu