Break out of an _.each loop

2019-04-10 10:27发布

问题:

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?

回答1:

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.

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.

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

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


回答2:

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

Maybe on a future version.