gpt4 book ai didi

javascript - 如何返回该对象数组的总计?

转载 作者:行者123 更新时间:2023-12-01 01:50:47 25 4
gpt4 key购买 nike

我需要计算这些的价格和税金并返回所有内容的总计。我正在学习,所以我对这个简单的问题表示歉意。

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;

最佳答案

只需使用 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);

关于javascript - 如何返回该对象数组的总计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com