我有一個包含專案的陣列。這些專案中的每一個都有以下值
invoice_rows: [
{ item: '', qty: '', price: '' }
],
對于每個發票專案,陣列中都添加了一行,但我想獲得所有這些專案的總成本。所以讓我們做一些數學運算,我有以下資料陣列
invoice_rows: [
{ item: 'item1', qty: '4', price: '10' }
{ item: 'item2', qty: '2', price: '10' }
{ item: 'item3', qty: '5', price: '5' }
],
總成本應該是每行的數量 * 價格的總和。使總數為 40 20 25 = 85。如何使用 reduce 方法做到這一點?
uj5u.com熱心網友回復:
const invoice_rows = [
{ item: 'item1', qty: '4', price: '10' },
{ item: 'item2', qty: '2', price: '10' },
{ item: 'item3', qty: '5', price: '5' },
];
const initialValue = 0;
const sumWithInitial = invoice_rows.reduce(
(previousValue, currentValue) => previousValue currentValue.qty*currentValue.price,
initialValue
);
console.log(sumWithInitial);
uj5u.com熱心網友回復:
給定
const invoice_rows = [
{ item: 'item1', qty: '4', price: '10' }
{ item: 'item2', qty: '2', price: '10' }
{ item: 'item3', qty: '5', price: '5' }
];
只需首先計算qty * price所有map專案,然后添加小計:
const total = invoice_rows.map(item => item.qty * item.price).reduce((a, b) => a b, 0);
請注意,JS 將隱式'4' * '10'轉換為 number 40。
uj5u.com熱心網友回復:
您只需從初始值 0 開始,然后將其減少如下...
const invoice_rows= [
{ item: 'item1', qty: '4', price: '10' },
{ item: 'item2', qty: '2', price: '10' },
{ item: 'item3', qty: '5', price: '5' }
];
const result = invoice_rows.reduce((previousValue, currentValue) => previousValue (currentValue.qty * currentValue.price), 0);
console.log(result)
希望這可以幫助。
uj5u.com熱心網友回復:
你可以做:
const invoice_rows = [
{ item: 'item1', qty: '4', price: '10' },
{ item: 'item2', qty: '2', price: '10' },
{ item: 'item3', qty: '5', price: '5' }
]
const result = invoice_rows.reduce((a, { qty, price }) => a qty * price, 0)
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468433.html
標籤:javascript
下一篇:為Swiper的幻燈片添加填充
