更好的实践:消除嵌套循环

Better Practices: Eliminate the nested loops?

本文关键字:嵌套循环 更好      更新时间:2023-09-26

我正在迭代一些对象,像这样(使用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);

使用Array.prototype.mapArray.prototype.reduce,存在一个充分表达的解:

var things = obj.Things.map(function (thing) {
    return thing.SubThings;
}).reduce(function (things, subthing) {
    return things.concat(subthing.SubSubThings);
}, []);

所有对象都是Array吗?

那么,这有意义吗?

var things = _.flatten(_.map(obj.Things, function(thing) {
    return _.pluck(thing.SubThings, "SubSubThings");
}));

如果你不想创造新的东西。

things.push(_.map(obj.Things, function(thing) {
  return _.pluck(thing.SubThings, "SubSubThings");
}));
things = _.flatten(things);