如何打破 underscore.js 中的 _.each 函数
我正在寻找一种方法来停止 underscore.js _.each()
方法的迭代,但找不到解决方案。如果您返回 false
,jQuery .each()
可能会中断。
有没有办法停止在each()下划线?
_([1,2,3]).each(function(v){
if (v==2) return /*what?*/;
})
I'm looking for a way to stop iterations of underscore.js _.each()
method, but can't find the solution. jQuery .each()
can break if you do return false
.
Is there a way to stop underscore each()?
_([1,2,3]).each(function(v){
if (v==2) return /*what?*/;
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您无法脱离
each
方法 - 它模拟本机forEach
方法的行为,并且本机forEach
不提供转义循环(除了抛出异常)。但是,我们并没有失去所有希望!您可以使用
Array.every
方法。 :)从该链接:
换句话说,你可以做一些像这样复杂的事情(链接到 JSFiddle):
这会提醒
1
到3
,然后“break”出循环。您正在使用 underscore.js,因此您会很高兴得知它确实提供了
every
方法 - 他们称之为every
,但正如该链接提到的,它们还提供了一个名为all
的别名。You can't break from the
each
method—it emulates the nativeforEach
method's behavior, and the nativeforEach
doesn't provide to escape the loop (other than throwing an exception).However, all hope is not lost! You can use the
Array.every
method. :)From that link:
In other words, you could do something convoluted like this (link to JSFiddle):
This will alert
1
through3
, and then "break" out of the loop.You're using underscore.js, so you'll be pleased to learn that it does provide an
every
method—they call itevery
, but as that link mentions, they also provide an alias calledall
.更新:
_.find 会更好,因为它在找到元素时会跳出循环:
** 旧 **
如果您想有条件地跳出循环,请使用 _.filter api 而不是 _.each。这是一个代码片段
Update:
_.find would be better as it breaks out of the loop when the element is found:
** Old **
If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet
您可以查看
_.some
而不是_.each
。一旦谓词为 true,
_.some
就会停止遍历列表。结果可以存储在外部变量中。
请参阅http://underscorejs.org/#some
You can have a look to
_.some
instead of_.each
._.some
stops traversing the list once a predicate is true.Result(s) can be stored in an external variable.
See http://underscorejs.org/#some
也许你想要Underscore的any()或find(),它们会在满足条件时停止处理。
Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.
就像其他答案一样,这是不可能的。
这是关于下划线断路器的评论 下划线问题 #21
Like the other answers, it's impossible.
Here is the comment about breaker in underscore underscore issue #21
您不能在下划线中中断
forEach
,因为它模拟 EcmaScript 5 本机行为。You cannot break a
forEach
in underscore, as it emulates EcmaScript 5 native behaviour.我相信如果您的数组实际上是一个对象,您可以使用空对象返回。
I believe if your array was actually an object you could return using an empty object.
http://underscorejs.org/#each
http://underscorejs.org/#each
更新:
您实际上可以通过在内部抛出错误并在外部捕获它来“中断”:如下所示:
这显然对您的代码在循环中触发的任何其他异常有一些影响,因此请谨慎使用!
Update:
You can actually "break" by throwing an error inside and catching it outside: something like this:
This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!
在我的案例中起作用
worked in my case