是否有可能突破每个循环的下划线..?突破_.each循环
_.each(obj, function(v,i){
if(i > 2){
break // <~ does not work
}
// some code here
// ...
})
有没有另一种设计模式可以使用?
是否有可能突破每个循环的下划线..?突破_.each循环
_.each(obj, function(v,i){
if(i > 2){
break // <~ does not work
}
// some code here
// ...
})
有没有另一种设计模式可以使用?
我不认为你可以,所以你只需要在i < 2
中包装函数的内容或使用return
。使用.some
或.every
可能更有意义。
编辑:
//pseudo break
_.each(obj, function (v, i) {
if (i <= 2) {
// some code here
// ...
}
});
问题与上面的当然是它必须做的整个循环,但这仅仅是下划线的each
的弱点。
你可以使用.every
,但(无论是本地阵列方法或下划线的方法):
_.every(obj, function (v, i) {
// some code here
// ...
return i <= 2;
});
你可以用代码示例展开这个答案吗? – 2013-12-20 09:59:49
@BillyMoon我更新了我的答案,包括例子 – 2013-12-20 14:44:57
p.s.从下划线文档(不知道最近如何): “an [each](http://underscorejs.org/#each)循环不能被打破 - 打破,使用[_.find](http: //underscorejs.org/#find)而不是“ – 2016-07-11 17:48:17
现在你不能打破的每个循环。它正在讨论这里:https://github.com/documentcloud/underscore/issues/596
也许在未来的版本。
我不知道Javascript,但不会“返回”工作? – Pubby 2013-04-26 20:25:00
@Pubby它会返回,并且循环会继续,并且它会再次返回。我想打破,并停止循环。 – 2013-04-26 20:26:05
您可以改用Array.every方法。 来自:http://stackoverflow.com/questions/8779799/how-to-break-the-each-function-in-underscore-js – oooyaya 2013-04-26 20:26:17