避免循环内循环

时间:2015-11-18 01:16:40

标签: javascript node.js

我想知道是否有办法避免循环内的循环,例如:

let underscore = require('underscore');

_.each(obj, (val, key) => {
  _.each(key, (val, key) => {
    _.each(key, (val, key) => {
       // Finally i have access to the value that i need
    });
  });
});

我正在处理一个复杂的MAP对象,它内部有地图和数组。很明显我不能替换循环..但我想知道我是否可以更改我的代码以使其更清晰。

感谢。

1 个答案:

答案 0 :(得分:2)

是的,您可以以比此处更清晰的方式破坏代码,以避免嵌套循环。假设你有这样的结构:

// lets invent some hash of people, where each person
// has an array of friends which are also objects
var people = {
    david: { friends: [{name:'mary'}, {name:'bob'}, {name:'joe'}] },
    mary: { friends: [{name:'bob'}, {name:'joe'}] }
};

function eatFriendBecauseImAZombie(myName, friendName) {
    console.log(myName + ' just ate ' + friendName + '!!');
}

// (inner loop 2) how to parse a friend
function parseFriend(myName, friend) {
    eatFriendBecauseImAZombie(myName, friend.name);
}

// (inner loop 1) how to parse a person
function parsePerson(name, info) {
  _.each(info.friends, (val) => parseFriend(name, val));
}

// (outer loop) loop over people
_.each(people, (val, key) => parsePerson(key, val));

输出是:

david just ate mary!!
david just ate bob!!
david just ate joe!!
mary just ate bob!!
mary just ate joe!!