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

后端 未结 11 1818
闹比i
闹比i 2020-11-28 20:49

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

相关标签:
11条回答
  • 2020-11-28 21:33

    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 {}; 
    });
    
    0 讨论(0)
  • 2020-11-28 21:33

    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!

    0 讨论(0)
  • 2020-11-28 21:34

    worked in my case

    var arr2 = _.filter(arr, function(item){
        if ( item == 3 ) return item;
    });
    
    0 讨论(0)
  • 2020-11-28 21:37

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

    http://underscorejs.org/#each

    0 讨论(0)
  • 2020-11-28 21:38

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

    0 讨论(0)
提交回复
热议问题