方案 1:设置条件(flag)
const arr = [0, 1, 2, 3, 4] const sum = arr.reduce((prev, curr, index, currArr) => { if (index >= 4) { return prev } else { prev += curr return prev } }, 0) console.log(sum) // 6
方案 2:循环过程中修改原始数组
const arr = [0, 1, 2, 3, 4] const sum = arr.reduce((prev, curr, index, currArr) => { prev += curr if (curr === 3) currArr.length = 0 return prev }, 0) console.log(sum) // 6
"如何跳出 reduce 循环"继续阅读