打破_.each循环 [英] Break out of an _.each loop

查看:124
本文介绍了打破_.each循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我认为你不能,所以你只需要在 i中包装该函数的内容< 2 或使用返回。使用 .some .every 可能更有意义。

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

编辑:

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

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

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

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

这篇关于打破_.each循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆