首页 > 解决方案 > 分配给 rValue

问题描述

收到有关此 reduce 功能的错误消息

一开始有这个

const populationTotal = 0;
let populationTotal = zooAnimals.reduce((populationTotal, populationAmount) => {
  return populationTotal + populationAmount.population;
}, 0);

console.log(populationTotal);

现在试试这个

const populationTotal = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const reducer = (populationTotal, 10) => populationTotal +

console.log(populationTotal.reduce(reducer));

收到 SyntaxError 错误:分配给右值 (190:34)

标签: javascriptarraysconstantsreduce

解决方案


  1. 您定义populationTotalconst然后尝试再次定义它并为其设置一个值。这不是const的工作方式。您只能在定义它的行将 value 设置为 const。

  2. Array.reduce与 、 和 参数一起使用accumulator,但current value主要与前两个一起使用。它还接受累加器的默认值作为其最后一个参数:indexarray

reducer 函数有四个参数:

  • 累加器 (acc)
  • 当前值(当前)
  • 当前指数 (idx)
  • 源数组 (src)

let data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// Used all four parameters but they are not needed specifically in this case, Just for illustration purposes
let result = data.reduce((acc, cur, idx, src) => acc + cur, 0)

console.log(result)

如果您想将 reducer 定义为一个单独的函数,您也可以:

const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const reducer = (acc, curr) => acc + curr

console.log(data.reduce(reducer, 0));


推荐阅读