javascript - 分配给 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)
解决方案
您定义
populationTotal
为const
然后尝试再次定义它并为其设置一个值。这不是const的工作方式。您只能在定义它的行将 value 设置为 const。Array.reduce与 、 和 参数一起使用
accumulator
,但current value
主要与前两个一起使用。它还接受累加器的默认值作为其最后一个参数:index
array
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));
推荐阅读
- javascript - 如何在没有for循环的情况下在控制台中显示数字?
- javascript - 如何使 react-datepicker 正确显示?
- jsp - 为什么我在 jsp 中的 for 循环中出现错误?
- docker - 重启后无法启动 docker 容器
- git - 在不获取其他分支的情况下增加浅克隆的深度
- javascript - 如何从数组中获取范围滑块内的值
- php - PDO 插入不接受“真”或“假”,但只接受 0 和 1
- c# - 实体框架并非全部检测模型上的更改
- mysql - 如何使用 ROW_NUMBER() 将行号添加到 MySQL 显示
- powershell - 在 Active Directory AD Powershell 中再次运行脚本