如何在underscore.js中打破_.each函数 [英] how to break the _.each function in underscore.js
问题描述
我正在寻找一种方法来停止underscore.js _。each()
方法的迭代,但无法找到解决方案。 jQuery .each()
如果你这样做就会中断 return false
。
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?*/;
})
推荐答案
你不能从每个
方法中断 - 它模仿原生 forEach
方法的行为,并且本机 forEach
不提供转义循环(除了抛出异常)。
You can't break from the each
method—it emulates the native forEach
method's behavior, and the native forEach
doesn't provide to escape the loop (other than throwing an exception).
但是,所有的希望都不会丢失!你可以使用 Array.every
方法。 :)
However, all hope is not lost! You can use the Array.every
method. :)
从该链接:
每个
为数组中的每个元素执行一次提供的回调
函数,直到找到一个回调
返回false值。如果找到这样的元素,每个
方法立即返回false。
every
executes the providedcallback
function once for each element present in the array until it finds one wherecallback
returns a false value. If such an element is found, theevery
method immediately returns false.
换句话说,你可以做这样令人费解的事情(链接到JSFiddle ):
In other words, you could do something convoluted like this (link to JSFiddle):
[1, 2, 3, 4].every(function(n) {
alert(n);
return n !== 3;
});
这将通过<$ c提醒 1
$ c> 3 ,然后退出循环。
This will alert 1
through 3
, and then "break" out of the loop.
你正在使用underscore.js,所以你将成为很高兴得知它 提供每个
方法 - 他们称之为 每个
,但正如该链接所提到的,它们还提供了一个名为 all
。
You're using underscore.js, so you'll be pleased to learn that it does provide an every
method—they call it every
, but as that link mentions, they also provide an alias called all
.
这篇关于如何在underscore.js中打破_.each函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!