代码之家  ›  专栏  ›  技术社区  ›  Kyle Underhill

数组中的和值

  •  -1
  • Kyle Underhill  · 技术社区  · 3 年前

    我正在努力获得 array 基于他们 type 然后在 total(item) 。结果返回连接的值,而不是总和。

    const App = (props) => {
      let array = [
        {
          amount: "12",
          amount2: "0",
          type: "Purchased"
        },
        {
          amount: "0",
          amount2: "34",
          type: "Donation"
        }
      ];
    
      const total = (data) => {
        let tempSub = [];
        let sum;
        if (data.length > 0) {
          data.map((i, k) => {
            let productTotal = i.amount;
            let donationTotal = i.amount2;
            tempSub.push(i.type === "Purchased" ? productTotal : donationTotal);
          });
          sum = tempSub.reduce(function (a, b) {
            return a + b;
          }, 0);
        } else {
          sum = 0;
        }
        return sum;
      };
      return (
        <>
          {array.length > 0
            ? array.map((item, i) => {
                return <>{total(item)}</>;
              })
            : ""}
        </>
      );
    };
    
    export default App;
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   BTSM    3 年前

    请在reduce回调函数中返回parseInt(a)+prseInt(b)