You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript/JQuery计算数组中OriginalPricetotal的总和?

计算数组中OriginalPricetotal字段的总和解决方案

没问题,我来帮你搞定这个计算需求!针对你给出的订单商品数组,这里有两种简单可靠的实现方式,不管是原生JavaScript还是jQuery都能轻松解决:

方法一:原生JavaScript reduce 方法(推荐)

reduce 是数组的原生方法,专门用来做累加这类聚合操作,代码简洁高效:

const products = [
  { "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" }
];

// 计算总和
const totalOriginalPrice = products.reduce((accumulator, currentItem) => {
  // 确保字段存在,避免undefined导致NaN
  return accumulator + (currentItem.OriginalPricetotal || 0);
}, 0); // 初始值设为0,保证空数组时返回0

console.log(totalOriginalPrice); // 输出:1053

解释一下:reduce 接收两个核心参数——累加器(accumulator)用来存储当前的总和,当前遍历项(currentItem)就是数组里的每个商品对象。最后设置初始值0,就算数组为空也能正常返回0,不会出现异常。

方法二:jQuery each 方法

如果你习惯用jQuery操作,也可以用$.each遍历数组累加:

const products = [
  { "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" }
];

let totalOriginalPrice = 0;

$.each(products, function(index, item) {
  // 同样做防错处理
  totalOriginalPrice += item.OriginalPricetotal || 0;
});

console.log(totalOriginalPrice); // 输出:1053

这种方法逻辑更直观:先初始化总和为0,然后遍历每个商品,把对应的OriginalPricetotal值加到总和里即可。

小提示

如果你的数组里可能存在没有OriginalPricetotal字段的元素,上面代码里的|| 0会把undefined或null转换成0,避免出现NaN的错误结果,让代码更健壮。

内容的提问来源于stack exchange,提问作者Akhila Prakash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:25:43