[英]Break out of an _.each loop
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
. 我认为你不能,所以你只需要在
i < 2
中包含函数的内容或者使用return
。 It may make more sense to use .some
or .every
. 使用
.some
或.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
. 与上面的问题当然是,它必须做的整个循环,但这仅仅是下划线的的弱点
each
。
You could use .every
, though (either native array method or underscore's method): 你可以使用
.every
(原生数组方法或下划线方法):
_.every(obj, function (v, i) {
// some code here
// ...
return i <= 2;
});
For now you cannot break an each loop. 现在你无法打破每个循环。 It is being discussed here: https://github.com/documentcloud/underscore/issues/596
这里将讨论它: https : //github.com/documentcloud/underscore/issues/596
Maybe on a future version. 也许在未来的版本上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.