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

基于价格表的价格计算器优化实现方案咨询

替代大量if判断的价格计算器实现方案

当价格规则存在大量变体时,硬编码if条件判断会导致代码臃肿、维护困难。推荐采用结构化配置数据+匹配逻辑的方案,核心思路是把所有价格规则存入JSON结构,通过遍历匹配获取对应价格,具体实现如下:

实现步骤

1. 定义价格配置数据

将所有条件组合与对应价格整理成数组,每个条目包含完整的匹配条件和价格值,新增/修改规则只需更新此配置:

const priceRules = [
  { type: "type1", size: "22", method: "method1", width: "150mm", price: 120 },
  { type: "type1", size: "30", method: "method1", width: "150mm", price: 150 },
  { type: "type2", size: "22", method: "method2", width: "200mm", price: 180 },
  // 按需添加更多规则
];

2. 编写匹配函数

遍历配置数组,找到与当前表单选中条件完全匹配的条目,返回对应价格:

function calculateTotal(selected) {
  const match = priceRules.find(rule => {
    return rule.type === selected.type &&
           rule.size === selected.size &&
           rule.method === selected.method &&
           rule.width === selected.width;
  });
  return match ? match.price : 0; // 无匹配时返回默认值
}

3. 表单交互逻辑

监听表单控件变化,收集当前选中的条件,调用匹配函数更新总价:

<form id="priceCalcForm">
  <select name="type">
    <option value="type1">类型1</option>
    <option value="type2">类型2</option>
  </select>
  <select name="size">
    <option value="22">尺寸22</option>
    <option value="30">尺寸30</option>
  </select>
  <select name="method">
    <option value="method1">方式1</option>
    <option value="method2">方式2</option>
  </select>
  <select name="width">
    <option value="150mm">150mm</option>
    <option value="200mm">200mm</option>
  </select>
  <div>总价:<span id="total">0</span></div>
</form>
const form = document.getElementById('priceCalcForm');
const totalEl = document.getElementById('total');

form.addEventListener('change', () => {
  const selectedConditions = {
    type: form.type.value,
    size: form.size.value,
    method: form.method.value,
    width: form.width.value
  };
  totalEl.textContent = calculateTotal(selectedConditions);
});

优化扩展

如果存在部分条件通用的规则,可以用*作为通配符简化配置,同时调整匹配逻辑:

// 带通配符的配置
const priceRules = [
  { type: "type1", size: "*", method: "method1", width: "150mm", price: 120 },
  // 匹配type1、任意size、method1、150mm的组合
];

// 支持通配符的匹配函数
function calculateTotal(selected) {
  const match = priceRules.find(rule => {
    return (rule.type === "*" || rule.type === selected.type) &&
           (rule.size === "*" || rule.size === selected.size) &&
           (rule.method === "*" || rule.method === selected.method) &&
           (rule.width === "*" || rule.width === selected.width);
  });
  return match ? match.price : 0;
}

内容的提问来源于stack exchange,提问作者s.Jay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:20:41