如何在每个循环中“继续”:下划线,node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18651100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:32:12  来源:igfitidea点击:

How to 'continue' inside a each loop : underscore, node.js

node.jsloopsunderscore.js

提问by Peter Lyons

The code in node.js is simple enough.

node.js 中的代码很简单。

_.each(users, function(u, index) {
  if (u.superUser === false) {
    //return false would break
    //continue?
  }
  //Some code
});

My question is how can I continue to next index without executing "Some code" if superUser is set to false?

我的问题是,如果 superUser 设置为 false,如何在不执行“某些代码”的情况下继续下一个索引?

PS: I know an else condition would solve the problem. Still curious to know the answer.

PS:我知道 else 条件可以解决问题。还是很想知道答案。

回答by Peter Lyons

_.each(users, function(u, index) {
  if (u.superUser === false) {
    return;
    //this does not break. _.each will always run
    //the iterator function for the entire array
    //return value from the iterator is ignored
  }
  //Some code
});

Side note that with lodash (not underscore) _.forEachif you DO want to end the "loop" early you can explicitly return falsefrom the iteratee function and lodash will terminate the forEachloop early.

旁注,使用 lodash(不是下划线),_.forEach如果您确实想提前结束“循环”,您可以return false从 iteratee 函数中明确显示,并且 lodash 将forEach提前终止循环。

回答by Vishnu PS

Instead of continuestatement in for loop you can use returnstatement in _.each()in underscore.js it will skip the current iteration only.

continue您可以在 underscore.js 中使用returnstatement in代替for 循环中的语句,_.each()它只会跳过当前迭代。

回答by pdoherty926

_.each(users, function(u, index) {
  if (u.superUser) {
    //Some code
  }
});