使用javascript / jquery的数组总和

时间:2018-04-13 06:54:24

标签: javascript jquery

[
   {
      "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"
   }
]

我想计算所有' OriginalPricetotal'的总和。在使用javascript / Jquery的数组中。我试过几种类型。但这不起作用。

2 个答案:

答案 0 :(得分:3)

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



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);




答案 1 :(得分:0)

您只需循环遍历数组并获取interface ViewShadow extends Pick<View, keyof View> { } class MobileDisplay implements ViewShadow { private content: any; protected presentation: string; public render() { console.log("View::render()"); console.log("content: ", this.content); console.log("presentation: ", this.presentation); } constructor(c: string, p: string) { this.content = c; this.presentation = p; } } 的值即可添加并获取总和。由于该值已经是数字而不是字符串,因此在添加之前不需要OriginalPricetotal来解析值:

使用forEach()

&#13;
&#13;
parseInt()
&#13;
&#13;
&#13;

使用地图()

&#13;
&#13;
var arr = [
   {
      "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 sum = 0;
arr.forEach(function(obj){
  sum += obj.OriginalPricetotal;
});

console.log(sum);
&#13;
&#13;
&#13;