Javascript减少生产总成本不起作用
Javascript reduce to produce a total cost not working
我正在尝试根据总计输出总成本,但似乎无法使用 .reduce 方法实现预期的功能。
我构建了一个“成本”数组,如下所示:
const costs = ["5.50", "1.00", "2.00", "1.50"]
然后我尝试将一个名为 totalCost 的变量分配给总计(已尝试使用 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
returns 一个 string.
怎么样:
costs.reduce((prev, current, index) => prev + parseFloat(current), 0).toFixed(2)
我正在尝试根据总计输出总成本,但似乎无法使用 .reduce 方法实现预期的功能。
我构建了一个“成本”数组,如下所示:
const costs = ["5.50", "1.00", "2.00", "1.50"]
然后我尝试将一个名为 totalCost 的变量分配给总计(已尝试使用 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
returns 一个 string.
怎么样:
costs.reduce((prev, current, index) => prev + parseFloat(current), 0).toFixed(2)