簡體   English   中英

如何返回該對象數組的總數?

[英]How do I return the total of this object array?

我需要承擔這些的價格和稅金,並退還所有款項。 我正在學習,因此我對這個簡單的問題表示歉意。

const orders = [{"price":15,"tax":0.09},{"price":42,"tax":0.07},{"price":56,"tax":0.11},
{"price":80,"tax":0.11},{"price":69,"tax":0.06},{"price":68,"tax":0.14},
{"price":72,"tax":0.14},{"price":51,"tax":0.09},{"price":89,"tax":0.15},
{"price":48,"tax":0.13}];
// Do not edit code above.

/*
  Use a higher order method to get the sum of all the order totals after adding in the sales tax
*/

var ordersTotal  = orders.reduce(function(total, num) {
    return total + num;
    })
  ordersTotal;

您需要給reduce開始一些東西,在這個例子中0可能是一個好的開始。 然后,傳遞給reduce每個num都是一個對象。 當前,您只是添加了諸如total = total + {"price":15,"tax":0.09} ,因此無法正常工作。 您需要查看要添加的每個屬性。 目前尚不清楚稅收是百分比還是總額。 在下面,我們將僅添加它,但是如果需要,應該清楚如何添加百分比。

 const orders = [{"price":15,"tax":0.09},{"price":42,"tax":0.07},{"price":56,"tax":0.11},{"price":80,"tax":0.11},{"price":69,"tax":0.06},{"price":68,"tax":0.14},{"price":72,"tax":0.14},{"price":51,"tax":0.09},{"price":89,"tax":0.15},{"price":48,"tax":0.13}]; var ordersTotal = orders.reduce(function(total, num) { return total + num.price + num.tax; // add properties }, 0) // start with 0 console.log(ordersTotal); 

只需使用Array.reduce()Object destructing即可 並且請確保將0作為初始值傳遞給reduce函數。

 const orders = [{"price":15,"tax":0.09},{"price":42,"tax":0.07},{"price":56,"tax":0.11},{"price":80,"tax":0.11},{"price":69,"tax":0.06},{"price":68,"tax":0.14},{"price":72,"tax":0.14},{"price":51,"tax":0.09},{"price":89,"tax":0.15},{"price":48,"tax":0.13}]; const result = orders.reduce((a,{price,tax})=>a+price+tax,0); console.log(result); 

確保以零開頭,這樣就不會嘗試將結果強制為字符串。

 const orders = [{"price":15,"tax":0.09},{"price":42,"tax":0.07},{"price":56,"tax":0.11}, {"price":80,"tax":0.11},{"price":69,"tax":0.06},{"price":68,"tax":0.14}, {"price":72,"tax":0.14},{"price":51,"tax":0.09},{"price":89,"tax":0.15}, {"price":48,"tax":0.13}]; // Do not edit code above. var ordersTotal = orders.reduce(function(total, order) { return total + order.price + order.tax; },0) console.log(ordersTotal,ordersTotal.toFixed(2)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM