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

如何优化JavaScript实现的商品阶梯价格计算程序?

阶梯计价代码优化方案

核心优化点

  • 抽离计价规则为独立配置,后续调整阶梯、单价无需修改计算逻辑,可维护性更强
  • 统一做参数合法性校验,避免重复的边界判断
  • 去掉冗余的重复计算代码,逻辑更简洁

优化实现(配置化版本,推荐)

这个版本适合计价规则可能后续调整的场景,改规则只要修改priceRules配置即可:

// 计价规则配置:upper为区间数量上限,exceedPrice为超出前10件后该区间的单价,按上限升序排列
const priceRules = [
  { upper: 10, exceedPrice: 10 },
  { upper: 50, exceedPrice: 9 },
  { upper: 100, exceedPrice: 8 },
  { upper: Infinity, exceedPrice: 7 }
]

function calculateTotal(qty) {
  // 参数合法性校验
  if (!Number.isInteger(qty) || qty < 1) {
    return "invalid value"
  }
  // 10件及以内直接计算
  if (qty <= 10) {
    return qty * 10
  }
  // 匹配对应区间的超出部分单价
  const matchedRule = priceRules.find(rule => qty <= rule.upper)
  return 10 * 10 + (qty - 10) * matchedRule.exceedPrice
}

// 测试示例
console.log(calculateTotal(9)) // 输出90
console.log(calculateTotal(11)) // 输出109
console.log(calculateTotal(50)) // 输出460
console.log(calculateTotal(101)) // 输出737

精简版本(规则固定场景可用)

如果确定计价规则不会变动,可以用更精简的三目运算实现,比原有的多层if分支更简洁:

function calculateTotal(qty) {
  if (!Number.isInteger(qty) || qty < 1) return "invalid value"
  const exceedPrice = qty <= 50 ? 9 : qty <= 100 ? 8 : 7
  return qty <= 10 ? qty * 10 : 100 + (qty - 10) * exceedPrice
}

内容的提问来源于stack exchange,提问作者Patel Abhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:15:03