Javascript 递归未完全遍历具有嵌套对象的对象
我打算编写一个模块,该模块可以用默认配置实例化,然后在初始化时用自定义配置重写。配置对象具有嵌套对象,因此如果自定义配置中包含这些嵌套对象,则需要遍历它们。我试图通过递归调用Javascript 递归未完全遍历具有嵌套对象的对象,javascript,recursion,tree-traversal,Javascript,Recursion,Tree Traversal,我打算编写一个模块,该模块可以用默认配置实例化,然后在初始化时用自定义配置重写。配置对象具有嵌套对象,因此如果自定义配置中包含这些嵌套对象,则需要遍历它们。我试图通过递归调用customize来实现这一点。这适用于第一个嵌套对象,但遍历在该对象之后结束。为什么会这样?我可以做些什么来完全遍历包含嵌套对象的对象 function Config(options) { function customize(conf) { if (conf && conf.co
customize
来实现这一点。这适用于第一个嵌套对象,但遍历在该对象之后结束。为什么会这样?我可以做些什么来完全遍历包含嵌套对象的对象
function Config(options) {
function customize(conf) {
if (conf && conf.constructor === Object) {
for (var prop in conf) {
if(conf[prop].constructor === Object) {
return customize.call(this[prop], conf[prop]);
} else {
if (this.hasOwnProperty(prop)){
this[prop] = conf[prop];
}
}
}
} else {
console.error('The first argument must be an object.');
return;
}
}
//Default config values
this.foo = 'default';
this.bar = {
foo: 'default'
};
this.baz = {
foo: 'default'
};
//Overide default config with custom config
if (options && options.constructor === Object) {
customize.call(this, options);
}
}
function TestModule(){
this.init = function(options){
this.config = (options && options.constructor === Object) ? new Config(options) : new Config();
return this;
};
}
console.log(
new TestModule().init({
foo: 'custom',
bar: {foo: 'custom'},
baz: {foo: 'custom'}
}).config
);
//RESULT
// {
// foo: 'custom',
// bar: {foo: 'custom'},
// baz: {foo: 'default'}
// }
这一行:
return customize.call(this[prop], conf[prop]);
在for循环中发生,因此在迭代每个项之前返回。您的return语句应该在循环之外。这是有效的。我的印象是递归调用总是作为
return
语句的一部分进行的。但显然,这样做结束了循环。