繁体   English   中英

计算 javascript 中数组对象的总和,TypeError: parseInt(...).reduce is not a function

[英]Calculating sum of array objects in javascript , TypeError: parseInt(...).reduce is not a function

我有一个带有数字的对象数组,但类型是字符串,我想将它们全部相加。

在此处输入图像描述

根据之前建议的有关堆栈溢出的答案,我正在这样做。

// Here the data has an array of goods which contains
// amount objects and i want to calculate to sum of amount objects
Total Invoice Price:
{data.goods
   ? data.goods.map((item) => (
    <div key={item.id}>
     <div>{parseInt(item.amount).reduce((a, b) => a + b, 0)}</div>
       </div >
       ))
     : null}

但是我收到错误TypeError: parseInt(...).reduce is not a function ,如何解决这个问题?

reduce是一种数组方法。 所以:不是映射数据,而是在 JSX 中调用 function,它返回数组中每个 object 的amount值的总和。

注意:如果您的金额值是字符串,则首先将它们强制转换为数字 ( Number(good.amount) )。

 function Example({ data }) { function getTotal(data) { return data.goods.reduce((acc, good) => { return acc + Number(good.amount); }, 0); } return ( <div> <h4>Total</h4> <p>{getTotal(data)}</p> </div> ); } const data = { goods: [{ amount: '1' }, { amount: '5' }, { amount: '13' }] }; ReactDOM.render( <Example data={data} />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

 goods = [{ amount: "11" }, { amount: "11" }, { amount: "11" }, ] let sum = goods.reduce((a, b) => a + parseInt(b.amount), 0) console.log(sum)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM