How to early break reduce() method?

后端 未结 12 1177
忘掉有多难
忘掉有多难 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:26

    You cannot break from inside of a reduce method. Depending on what you are trying to accomplish you could alter the final result (which is one reason you may want to do this)

    const result = [1, 1, 1].reduce((a, b) => a + b, 0); // returns 3
    
    console.log(result);

    const result = [1, 1, 1].reduce((a, b, c, d) => {
      if (c === 1 && b < 3) {
        return a + b + 1;
      } 
      return a + b;
    }, 0); // now returns 4
    
    console.log(result);

    Keep in mind: you cannot reassign the array parameter directly

    const result = [1, 1, 1].reduce( (a, b, c, d) => {
      if (c === 0) {
        d = [1, 1, 2];
      } 
      return a + b;
    }, 0); // still returns 3
    
    console.log(result);

    However (as pointed out below), you CAN affect the outcome by changing the array's contents:

    const result = [1, 1, 1].reduce( (a, b, c, d) => {
      if (c === 0) {
        d[2] = 100;
      } 
      return a + b;
    }, 0); // now returns 102
    
    console.log(result);

提交回复
热议问题