How to early break reduce() method?

后端 未结 12 1178
忘掉有多难
忘掉有多难 2020-11-28 05:44

How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <=         


        
12条回答
  •  北海茫月
    2020-11-28 06:27

    There is no way, of course, to get the built-in version of reduce to exit prematurely.

    But you can write your own version of reduce which uses a special token to identify when the loop should be broken.

    var EXIT_REDUCE = {};
    
    function reduce(a, f, result) {
      for (let i = 0; i < a.length; i++) {
        let val = f(result, a[i], i, a);
        if (val === EXIT_REDUCE) break;
        result = val;
      }
      return result;
    }
    

    Use it like this, to sum an array but exit when you hit 99:

    reduce([1, 2, 99, 3], (a, b) => b === 99 ? EXIT_REDUCE : a + b, 0);
    
    > 3
    

提交回复
热议问题