gpt4 book ai didi

javascript - 使用 javascript/jquery 计算数组的总和

转载 作者:行者123 更新时间:2023-11-28 17:33:16 25 4
gpt4 key购买 nike

[
{
"ProductId": 177,
"Quantity": 3,
"Price": 1,
"OriginalPrice": 1,
"OriginalPricetotal": 3,
"SoldPrice": 1,
"ProductName": "Hand Spinners"
},
{
"ProductId": 30207,
"Quantity": 2,
"Price": 525,
"OriginalPrice": 525,
"OriginalPricetotal": 1050,
"SoldPrice": 525,
"ProductName": "Clay Home"
}
]

我想使用 javascript/Jquery 计算数组中所有“OriginalPricetotal”的总和。我尝试了几种类型。但这是行不通的。

最佳答案

请参阅下面的代码片段,它将返回您想要的答案

var obj = [
{
"ProductId": 177,
"Quantity": 3,
"Price": 1,
"OriginalPrice": 1,
"OriginalPricetotal": 3,
"SoldPrice": 1,
"ProductName": "Hand Spinners"
},
{
"ProductId": 30207,
"Quantity": 2,
"Price": 525,
"OriginalPrice": 525,
"OriginalPricetotal": 1050,
"SoldPrice": 525,
"ProductName": "Clay Home"
}
];

var ans = 0;
// Better option
obj.forEach(function(value){
ans = ans + value.OriginalPricetotal
});
console.log(ans);

ans = 0;
//obj.map(o => ans = ans + o.OriginalPricetotal); //ES6
obj.map(function(value){
ans = ans + value.OriginalPricetotal
});
console.log(ans);

关于javascript - 使用 javascript/jquery 计算数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49810970/

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