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:34

worked in my case

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});
查看更多
叛逆
3楼-- · 2019-01-06 09:35

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

查看更多
我只想做你的唯一
4楼-- · 2019-01-06 09:37

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 {}; 
});
查看更多
可以哭但决不认输i
5楼-- · 2019-01-06 09:38

Update:

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

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

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"}
查看更多
唯我独甜
6楼-- · 2019-01-06 09:38
_([1,2,3]).find(function(v){
    return v if (v==2);
})
查看更多
登录 后发表回答