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?
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 usereturn
. It may make more sense to use.some
or.every
.EDIT:
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):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.