【问题标题】:Why is this recursive function overwriting the values of the second call?为什么这个递归函数会覆盖第二次调用的值?
【发布时间】:2019-07-24 05:13:35
【问题描述】:

对不起标题,我什至不知道如何表达这里发生的事情。

我正在开发一个支持多种货币的 React 费用跟踪程序。被跟踪的费用可以任意嵌套在 JSON 对象中。

entertainment: {
  _values: {
    USD: 23,
    AUD: 5,
  },
  'food & drink': {
    _values: {
      AUD: 83,
    },
    'local bar': {
      _values: {
        AUD: 28,
        USD: 2,
      },
    },
  },
  minigolf: {
    _values: {
      USD: 112,
    },
  }
}

费用可以直接存储金额,但它也可以作为“父”类别来进一步详细的子费用。

为了显示支出的总价值,我编写了两个函数: sumValues(values) 汇总_values 对象的数组(值对象是货币代码和整数的键值存储)

totalExpense(expense) 返回费用的总值。即它拥有的任何_values,+ 任何儿童费用的总费用。

我以为我已经将这些编写为纯函数,但是当递归调用 totalExpense() 时,费用的第一个子项返回错误的总数。

totalExpense(entertainment);
//-> Object { USD: 137, AUD: 116 }

好的

totalExpense(entertainment['food & drink']);
//-> Object { AUD: 111, USD: 2 }

好的

totalExpense(entertainment);
totalExpense(entertainment['food & drink']);
//-> Object { AUD: 139, USD: 4 }

不行

我一直在研究这段代码好几个小时了,但我一辈子都看不到发生了什么:

  sumValues = values => {
    return values.reduce((acc, cur) => {
      for (const currency in cur) {
        acc[currency]
          ? (acc[currency] = acc[currency] + cur[currency])
          : (acc[currency] = cur[currency]);
      }
      return acc;
    });
  };
  totalExpense = expense => {
    const values = [];

    if (expense['_values']) {
      values.push(expense['_values']);
    }

    const subExpenses = Object.keys(expense).filter(child => {
      return child[0] !== '_';
    });

    if (subExpenses.length > 0) {
      for (const subExpense of subExpenses) {
        let subtotal = this.totalExpense(expense[subExpense]);
        values.push(subtotal);
      }
    }

    if (values.length) {
      return this.sumValues(values);
    } else {
      throw Error('No values in this expense');
    }
  };
  render() {
    const entertainment = {
      _values: {
        USD: 23,
        AUD: 5,
      },
      'food & drink': {
        _values: {
          AUD: 83,
        },
        'local bar': {
          _values: {
            AUD: 28,
            USD: 2,
          },
        },
      },
      minigolf: {
        _values: {
          USD: 112,
        },
      },
    };

    console.log(this.totalExpense(entertainment));
    console.log(this.totalExpense(entertainment['food & drink']));
    console.log(this.totalExpense(entertainment['minigolf']));

    return;
  }

【问题讨论】:

  • 没有 JSON 对象 这样的东西。 JSON 总是 一个字符串。

标签: javascript reactjs ecmascript-6 functional-programming


【解决方案1】:

问题是您的reduce 回调的初始值是values 数组中的第一项,然后您继续分配给该项:

    acc[currency]
      ? (acc[currency] = acc[currency] + cur[currency])
      : (acc[currency] = cur[currency]);

因此,每次调用 sumValues 时,第一项都会发生变化。相反,提供一个空对象作为reduce 的初始值:

 sumValues = values => {
    return values.reduce((acc, cur) => {
      for (const currency in cur) {
        acc[currency]
          ? (acc[currency] = acc[currency] + cur[currency])
          : (acc[currency] = cur[currency]);
      }
      return acc;
    }, {});
  };

sumValues = values => {
  return values.reduce((acc, cur) => {
    for (const currency in cur) {
      acc[currency] ?
        (acc[currency] = acc[currency] + cur[currency]) :
        (acc[currency] = cur[currency]);
    }
    return acc;
  }, {});
};
totalExpense = expense => {
  const values = [];

  if (expense['_values']) {
    values.push(expense['_values']);
  }

  const subExpenses = Object.keys(expense).filter(child => {
    return child[0] !== '_';
  });

  if (subExpenses.length > 0) {
    for (const subExpense of subExpenses) {
      let subtotal = this.totalExpense(expense[subExpense]);
      values.push(subtotal);
    }
  }
  if (values.length) {
    return this.sumValues(values);
  } else {
    throw Error('No values in this expense');
  }
};
const entertainment = {
  _values: {
    USD: 23,
    AUD: 5,
  },
  'food & drink': {
    _values: {
      AUD: 83,
    },
    'local bar': {
      _values: {
        AUD: 28,
        USD: 2,
      },
    },
  },
  minigolf: {
    _values: {
      USD: 112,
    },
  },
};

console.log(totalExpense(entertainment));
console.log(totalExpense(entertainment['food & drink']));

【讨论】:

  • 做到了!非常感谢。我只是假设它传递了初始值的副本,而不是值本身....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 2012-05-29
相关资源
最近更新 更多