Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 避免循环内的循环_Javascript_Node.js - Fatal编程技术网

Javascript 避免循环内的循环

Javascript 避免循环内的循环,javascript,node.js,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 }); }); }); 我正在处理一个复

我想知道是否有任何方法可以避免循环中的循环,例如:

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对象,它的内部有贴图和数组。很明显,我无法更换这些回路。。但我想知道我是否可以更改代码以使其更清晰


谢谢。

是的,您可以用比这里更干净的方式分解代码,以避免嵌套循环。假设你有一个这样的结构:

// 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!!

是的,有办法。@squint从技术上讲,你已经回答了这个问题…@squint,还有其他办法too@kapetanios那是一个恶毒的谣言@见鬼,甚至还有更好的方法…