javascript 跳出 _.each 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16244640/
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-10-27 03:52:46  来源:igfitidea点击:

Break out of an _.each loop

javascriptunderscore.jsbreak

提问by Billy Moon

Is it possible to break out of an underscore each loop..?

是否有可能打破每个循环的下划线..?

_.each(obj, function(v,i){
  if(i > 2){
    break // <~ does not work
  }
  // some code here
  // ...
})

Is there another design pattern I can be using?

我可以使用另一种设计模式吗?

回答by Explosion Pills

I don't think you can, so you will just have to wrap the contents of the function in i < 2or use return. It may make more sense to use .someor .every.

我认为您不能,因此您只需要将函数的内容包装在i < 2或使用return. 使用.someor可能更有意义.every

EDIT:

编辑:

//pseudo break
_.each(obj, function (v, i) {
    if (i <= 2) {
        // some code here
        // ...
    }
});

The issue with the above is of course that it has to do the entire loop, but that is simply a weakness of underscore's each.

上面的问题当然是它必须完成整个循环,但这只是下划线的弱点each

You could use .every, though (either native array method or underscore's method):

不过,您可以使用.every(本机数组方法或下划线方法):

_.every(obj, function (v, i) {
    // some code here
    // ...
    return i <= 2;
});

回答by adpmatos

For now you cannot break an each loop. It is being discussed here: https://github.com/documentcloud/underscore/issues/596

现在你不能打破每个循环。这里正在讨论:https: //github.com/documentcloud/underscore/issues/596

Maybe on a future version.

也许在未来的版本中。