将两个对象与多个节点组合在一起——为什么这段代码有效

Combing two objects with multiple nodes - why does this code work?

本文关键字:为什么 段代码 代码 有效 在一起 节点 两个 对象 组合      更新时间:2023-09-26

我有一个用于存储多个值/对象的对象,只有当存储对象中不存在当前节点时,我才希望能够添加值/节点(我不希望"I"值覆盖"data.pageData"中的数据集-示例中的值1、值2和值3)。我不知道我想添加的节点有多深,所以代码必须处理无限数量的对象级别。这就是我写的,它就像我需要它一样工作,但我不知道为什么。

我不明白为什么最后返回data.pageData是返回两级或三级深层对象。我认为封装会阻止返回值。

var data = {
    pageData: {
        value1: true,
        value2: 'not an empty string',
        other: {
            value3: false
        }
    }
};
var i = {
    value1: false,
    value2: '',
    other: {
        value3: true,
        value4: {
            value5: true
        },
        value6: 100
    }
};
init('pageData', i);
console.log(JSON.stringify(data));
function init(name, input) {
    if (typeof input !== 'object') {
        console.error('expected input as an object.');
        return;
    }
    var transverseObj = function(i, d) {
        for (var prop in i) {
            if (i.hasOwnProperty(prop)) {
                if (typeof i[prop] === 'object' && typeof d[prop] !== 'undefined') transverseObj.call(transverseObj(i[prop], d[prop]));
                if (typeof d[prop] === 'undefined') d[prop] = i[prop];
            }
        }
        return d;
    };
    //// Check if the storage object is undefined, otherwise run through the object(s)
    data[name] = typeof data[name] === 'undefined' ? input : transverseObj(i, data[name]);
}

您的代码之所以有效,是因为您在递归调用中传递对象图节点的直接引用,即您在原地更改目标对象,而不是返回新对象。