【问题标题】:Reduce function only working once in JavaScript code [duplicate]减少功能仅在JavaScript代码中工作一次[重复]
【发布时间】:2021-03-13 22:41:10
【问题描述】:

我目前必须使用 Array.reduce 方法的函数,但只有第一个函数有效。

let profit = incomes.reduce((a,b) => a.getAmount() + b.getAmount());

其中 a = 具有方法 getAmount 的自定义 BudgetItem 类。我想知道这是一个常见的 JS 事情还是我做错了什么。

请注意,我已经使用调试器进行了检查,并输入了这一行,我在两种方法中都有相同的数据。

【问题讨论】:

标签: javascript


【解决方案1】:

根据 mozilla,Array.reduce() 中的第一个参数是累加器(当前总和),第二个是数组中的当前值

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


因此,如果您尝试对 BudgetItem 数组中的值求和,您将需要类似:

let profit = incomes.reduce((currentTotal, curremtIncome) => currentTotal + curremtIncome.getAmount());

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多