我想知道有没有办法避免循环内循环,例如:
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 对象,它内部有 map 和数组。很明显我不能替换循环..但我想知道我是否可以更改我的代码以使其更清晰。
谢谢。
最佳答案
是的,您可以使用比此处更简洁的方式分解代码以避免嵌套循环。假设您有这样的结构:
// 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!!
关于javascript - 避免循环内循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770144/