簡體   English   中英

更好的做法:消除嵌套循環?

[英]Better Practices: Eliminate the nested loops?

我正在遍歷像這樣的一些對象(使用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);

所有對象都是數組嗎?

然后,這有意義嗎?

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);

使用Array.prototype.mapArray.prototype.reduce ,存在一種足夠表達的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM