我正在遍历像这样的一些对象(使用Underscore.js):
_.each(obj.Things, function(thing) {
_.each(thing.SubThings, function(subThing) {
_.each(subThing.SubSubThing, function(subSubThing) {
things.push(subSubThing);
});
});
});
从架构上来说,我不喜欢它的外观。有没有一种更清洁的方式来完成这样的任务?
最佳答案
提高代码可读性的一种方法是取消嵌套调用并仅使用常规函数调用。
_.each(obj.Things, processThing);
function processThing(thing) {
_.each(thing.SubThings, processSubThing);
}
function processSubThing(subThing) {
_.each(subThing.SubSubThing, processSubSubThing);
}
function processSubSubThin(subSubThing) {
things.push(subSubThing);
}
如果使用ES6 / ES2015,则可以使用箭头功能
let processThing = thing => _.each(thing.SubThings, processSubThing);
let processSubThing = subThing => _.each(subThing.SubSubThing, processSubSubThing);
let processSubSubThin = subSubThing => things.push(subSubThing);
_.each(obj.Things, processThing);