Javareduce是否可以正常工作?

时间:2018-08-16 13:32:29

标签: javascript arrays reduce ecmascript-5

下面的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

0 个答案:

没有答案