【问题标题】:How to 'continue' inside a each loop : underscore, node.js如何在每个循环中“继续”:下划线,node.js
【发布时间】:2013-09-10 03:50:18
【问题描述】:

node.js 中的代码很简单。

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

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

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

【问题讨论】:

    标签: node.js loops underscore.js


    【解决方案1】:
    _.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
    });
    

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

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      _.each(users, function(u, index) {
        if (u.superUser) {
          //Some code
        }
      });
      

      【讨论】:

      • 对不起。我应该详细说明场景。如果超级用户为假,我需要执行一些代码然后继续。还有另一种情况,如果(超级用户!= false && 已激活)我需要执行其他操作并执行“某些代码”,然后还有其他情况需要执行“某些代码”。我只是想知道是否有一种方法可以做到这一点,而无需在 else if 和 else 中重写相同的代码。我不想为此创建另一个函数。
      • 他在问如何避免这种非常糟糕的箭头代码实践。
      猜你喜欢
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多