递归函数中的内存中的对象值(堆栈?)?

时间:2018-06-10 09:25:24

标签: javascript recursion

我在SO上发现了一段很好的代码,我只是部分理解。如果你可以帮助我理解这个递归函数的第二个循环中myObj发生了什么,当函数不再指向myObj时(相反它指向tmpObj但它仍然添加到它

  var myObj = {};

function addProps(obj, arr, val) { // in the first run obj = myObj

    if (typeof arr == 'string')
        arr = arr.split(".");

    obj[arr[0]] = obj[arr[0]] || {};

    var tmpObj = obj[arr[0]];

    if (arr.length > 1) {
        arr.shift();
        addProps(tmpObj, arr, val); // whilst recursing, tmpObj becomes obj (as function parameter), so why myObj keeps being changed as well?
    }
    else
        obj[arr[0]] = val;

    return obj;

};

addProps(myObj, 'sub1.sub2.propA', 1);

链接到原始代码: https://stackoverflow.com/a/34205057

1 个答案:

答案 0 :(得分:0)

当你有一个嵌套对象并且改变了内部对象时,没有涉及复制......外部对象仍然指向同一个(现在是变异的)内部对象,例如:



const myObj = {a: {b: 'c'}}
const tmpObj = myObj.a
tmpObj.b = 'd'
console.log('original mutated after changing the inner object:', myObj)

const copyObj = Object.assign({}, myObj.a) // or {...myObj.a}
copyObj.b = 'e'
console.log('original NOT mutated after changing a copy:', myObj)