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 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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With