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

2019-01-06 09:04发布

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?*/;
})

11条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-06 09:19

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

查看更多
Fickle 薄情
3楼-- · 2019-01-06 09:23

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

查看更多
家丑人穷心不美
4楼-- · 2019-01-06 09:25

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.

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

See http://underscorejs.org/#some

查看更多
老娘就宠你
5楼-- · 2019-01-06 09:26

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!

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-06 09:29

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).

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

From that link:

every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false.

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;
});

This will alert 1 through 3, 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 it every, but as that link mentions, they also provide an alias called all.

查看更多
Ridiculous、
7楼-- · 2019-01-06 09:34

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

http://underscorejs.org/#each

查看更多
登录 后发表回答