繁体   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