下面的javascript reduce函数产生错误的总和,是吗?
请帮助我理解为什么?
获得正确金额的正确方法是什么?
const array1 = [2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91
console.log(array1.reduce(reducer));
// 5 + 2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,2.01,1.91
console.log(array1.reduce(reducer, 5));
结果:
19.999999999999996 24.999999999999996
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce