gpt4 book ai didi

javascript - 更好的做法 : Eliminate the nested loops?

转载 作者:行者123 更新时间:2023-12-03 08:50:24 26 4
gpt4 key购买 nike

我正在迭代一些对象,如下所示(使用 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);

关于javascript - 更好的做法 : Eliminate the nested loops?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com