打破_.each循环

Bil*_*oon 4 javascript break underscore.js

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

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

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

Exp*_*lls 9

我不认为你可以,所以你只需要将函数的内容包装i < 2或使用return.使用.some或更有意义.every.

编辑:

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

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

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

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