如何在 Array.prototype.reduce() 中预定义累加器?

How can I predefine the accumulator in Array.prototype.reduce()?

我需要从数组中的特定索引向彼此添加项目。

function findEvenIndex(arr) {
  let leftsum = 0;
  let rightsum = 0;
  arr.forEach((el, ind) => {
    arr.reduce((acc, currv, i) => i > ind + 1 ? acc + currv : 0) //acc = 1 or undefined
    leftsum += arr[ind + 1];
    rightsum += arr[ind - 1]
  })
}

我希望累加器等于 ind+1。我应该怎么做?

How can I predefine the accumulator in Array.prototype.reduce()?

只需将第二个参数提供给 reduce:

arr.reduce ((acc, currv, i) => i > ind+1 ? acc+currv : 0, ind + 1)
// -------------------------------------------------------^^^^^^^

但是如果您没有使用 return 值,那么使用 reduce 是没有意义的。 reduce 调用实际上是空操作。您没有使用结果,回调中没有副作用。


我问这个功能是做什么的,你在评论中回复:

I need to take an array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N.

要做到这一点,我会从尽可能靠近中间的地方开始,然后慢慢地走到边缘。显然你不希望我 post 一个解决方案,但我会选择中点索引,从该索引计算每个方向的总和,然后只要总和不匹配,就尝试向左移动一个放置(从左侧总和中减去新索引处的值并将其添加到右侧)并检查。然后尝试向右移动一个位置(从右边的总和中减去新索引处的值并将其添加到左侧)并检查。继续前进,直到 运行 进入边缘。