Javascript 如何打破underscore.js中的_.each函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8779799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:29:15  来源:igfitidea点击:

how to break the _.each function in underscore.js

javascriptjqueryunderscore.js

提问by dy_

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.

我正在寻找一种方法来停止 underscore.js_.each()方法的迭代,但找不到解决方案。.each()如果你这样做,jQuery可能会崩溃return false

Is there a way to stop underscore each()?

有没有办法停止每个()下划线?

_([1,2,3]).each(function(v){
    if (v==2) return /*what?*/;
})

回答by aeskr

You can't break from the eachmethod—it emulates the native forEachmethod's behavior, and the native forEachdoesn't provide to escape the loop (other than throwing an exception).

你不能中断each方法——它模拟本地forEach方法的行为,本地forEach不提供转义循环(除了抛出异常)。

However, all hope is not lost!You can use the Array.everymethod. :)

然而,所有的希望都没有消失!您可以使用该Array.every方法。:)

From that link:

从该链接:

everyexecutes the provided callbackfunction once for each element present in the array until it finds one where callbackreturns a false value. If such an element is found, the everymethod immediately returns false.

everycallback对数组中存在的每个元素执行一次提供的函数,直到找到一个callback返回假值的函数。如果找到这样的元素,该every方法会立即返回 false。

In other words, you could do something convoluted like this (link to JSFiddle):

换句话说,你可以做一些像这样复杂的事情(链接到 JSFiddle):

[1, 2, 3, 4].every(function(n) {
    alert(n);
    return n !== 3;
});

This will alert 1through 3, and then "break" out of the loop.

这将1通过3发出警报,然后“中断”循环。

You're using underscore.js, so you'll be pleased to learn that it doesprovide an everymethod—they call it every, but as that link mentions, they also provide an alias called all.

您正在使用 underscore.js,因此您会很高兴地了解到它确实提供了一个every方法——他们称之为every,但正如该链接提到的,他们还提供了一个名为 的别名all

回答by Nikhil

Update:

更新:

_.find would be better as it breaks out of the loop when the element is found:

_.find 会更好,因为它在找到元素时跳出循环:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

** 老的 **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

如果您想有条件地跳出循环,请使用 _.filter api 而不是 _.each。这是一个代码片段

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

回答by Joan

You can have a look to _.someinstead of _.each. _.somestops traversing the list once a predicate is true. Result(s) can be stored in an external variable.

你可以看看 to_.some而不是_.each_.some一旦谓词为真,就停止遍历列表。结果可以存储在外部变量中。

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

See http://underscorejs.org/#some

http://underscorejs.org/#some

回答by Rockyboy_ruby

_([1,2,3]).find(function(v){
    return v if (v==2);
})

回答by JaredMcAteer

You cannot break a forEachin underscore, as it emulates EcmaScript 5 native behaviour.

您不能forEach在下划线中打断 a ,因为它模拟了 EcmaScript 5 的本机行为。

回答by grantwparks

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

也许您想要 Underscore 的 any() 或 find(),它们将在满足条件时停止处理。

回答by czizzy

Like the other answers, it's impossible. Here is the comment about breaker in underscore underscore issue #21

像其他答案一样,这是不可能的。这是关于下划线下划线问题 #21 中的断路器的评论

回答by bm_i

I believe if your array was actually an object you could return using an empty object.

我相信如果您的数组实际上是一个对象,您可以使用空对象返回。

_.({1,2,3,4,5}).each(function(v){  
  if(v===3) return {}; 
});

回答by percebus

It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

还需要注意的是,不能打破 each 循环——要打破,请改用 _.find。

http://underscorejs.org/#each

http://underscorejs.org/#each

回答by bm_i

Update:

更新:

You can actually "break" by throwing an error inside and catching it outside: something like this:

实际上,您可以通过在内部抛出错误并在外部捕获错误来“中断”:如下所示:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!

这显然对您的代码在循环中触发的任何其他异常有一些影响,因此请谨慎使用!