Javascript降低了生产的总成本,不起作用



我试图根据总额输出总成本,但使用.reduce方法似乎无法实现预期功能。

我建立了一个";"成本";阵列向上,看起来像这样:

const costs = ["5.50", "1.00", "2.00", "1.50"]

然后,我尝试将一个名为totalCost的变量分配给totals(已经尝试了parseFloat((.toFixed(2(方法的各种方法,但没有得到所需的结果。

// Returns prev is not defined (2nd instance)
const totalCost = costs.reduce((prev, current, index) => prev, parseFloat(prev + current).toFixed(2), 0);
// Returns prev is not defined due to mismatch of values associated to the arguments
const totalCost = costs.reduce((prev, current, index) => prev + parseFloat(current).toFixed(2), 0);

结果总是5.50(数组中的第一个值(或一个将它们全部附加的字符串。

也尝试过forEach。和带有parseFloat((的值的直+。toFixed(2(

任何指向正确方向的分数都会很感激,因为我觉得它就快到了,但在过去的一个小时左右,我一直在用头撞墙。

您第一次尝试时遇到的问题costs.reduce((prev, current, index) => prev, parseFloat(prev + current).toFixed(2), 0);

语言无法将prev,上的逗号区分为函数的末尾或自变量的末尾。因此它认为parseFloat...是reduce函数的下一个自变量。

第二个问题是toFixed返回字符串

怎么样:

costs.reduce((prev, current, index) => prev + parseFloat(current), 0).toFixed(2)

最新更新