我需要承担这些的价格和税费,并退还所有款项。我正在学习,因此我对这个简单的问题表示歉意。
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;
答案 0 :(得分:1)
您需要从头开始减少一些内容,在此示例中,0
可能是一个好的开始。然后,每个传递给num
的{{1}}将成为一个对象。当前,您只是添加了reduce
之类的对象,因此无法正常工作。您需要查看要添加的每个属性。目前尚不清楚税收是百分比还是总额。在下面,我们只添加它,但是如果需要,应该清楚如何添加百分比。
total = total + {"price":15,"tax":0.09}
答案 1 :(得分:1)
只需使用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);
答案 2 :(得分:0)
确保以零开头,这样就不会尝试将结果强制为字符串。
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))