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

如何使用JavaScript的reduce方法实现按数量核算促销价和常规价

促销价格计算实现方案

核心逻辑以2件为一个促销单位拆分商品数量,分别计算促销部分和零散部分的价格,仅对设置了salesPrice的商品应用优惠规则:

  • 促销组数量:取商品数量除以2的整数部分,每组按salesPrice计算
  • 零散件数量:取商品数量模2的结果,每件按原价price计算
  • 无salesPrice的普通商品直接按原价乘以数量计算

改造后的计算代码

const gross = compiledCart.reduce((sum, { price, quantity, salesPrice }) => {
  // 有促销价的商品走优惠规则
  if (salesPrice) {
    const promotionCount = Math.floor(quantity / 2)
    const remainingCount = quantity % 2
    return sum + promotionCount * salesPrice + remainingCount * price
  }
  // 普通商品走原价计算
  return sum + price * quantity
}, 0)

效果验证

以你给出的购物车数据为例:

  • 糖果:数量3,促销价5,原价3.97
    促销组数量为Math.floor(3/2) =1,零散件数量为3%2=1,总价为1*5 + 1*3.97 = 8.97
  • 面包:数量1,无促销价,总价为1*2.17 = 2.17
  • 最终总金额为8.97 +2.17 =11.14,完全符合你描述的促销规则

内容的提问来源于stack exchange,提问作者n-dev-101

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 22:06:00