开发者问题收集

JAVASCRIPT REDUCER 不与上下文一起累积

2020-09-08
49

建立一个演示预算并且我的代码可以运行,但是费用数组并未在下面的函数中累积。

        {value => {
            const totalExpense = value.expenses.length > 0 ? (
                value.expenses.reduce((acc, curr) => {
                    acc += curr.amount
                    return acc
                }, 0)) : 0;
            console.log(totalExpense);
            console.log(value.expenses);
2个回答

在我的计算机上有效。

如果不知道数据是什么样子就很难说,所以我在下面进行了尝试:

const value = {
  expenses: [{amount: 1}, {amount: 2}]
}

const totalExpense = value.expenses.length > 0 ? (
  value.expenses.reduce((acc, curr) => {
    acc += curr.amount
    return acc
  }, 0)) : 0;
  
console.log(totalExpense);
console.log(value.expenses);

您还可以通过以下更改进一步简化它:

const value = {
  expenses: [{amount: 1}, {amount: 2}]
}

// no need to check length
const totalExpense = value.expenses.reduce((acc, curr) => acc + curr.amount, 0);
  
console.log(totalExpense);
console.log(value.expenses);
Soc
2020-09-08
        {value => {
            const totalExpense = value.expenses.length > 0 ? (
                value.expenses.reduce((acc, curr) => {
                    acc += parseInt(curr.amount)
                    return acc
                }, 0)) : 0;
            console.log(totalExpense);
            console.log(value.expenses);

cure.amount 不是整数,因此需要将其解析为 parseInt

J.Scott Glover
2020-09-09