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

如何实现购物车输入数量的数组规则校验与对应价格匹配?

阶梯价格匹配的简洁实现方案

这是个典型的阶梯定价场景,你的需求核心是根据输入数量匹配对应的价格区间,而非仅精准匹配数量值。我给你几个简洁优雅的实现方式,完全贴合你的规则:

先明确规则(基于你的示例)

根据你给出的示例,我们可以把规则转化为清晰的区间:

  • 0 < 数量 ≤ 2 → 单价20.0000
  • 2 < 数量 ≤ 4 → 单价15.0000
  • 4 < 数量 ≤ 8 → 单价10.0000
  • 数量 > 8 → 默认使用最后一档单价10.0000(可根据需求调整)

第一步:预处理规则数组

首先把数组里的字符串数值转为浮点数,同时确保数组按qty升序排列(原数组已经符合,但排序能让代码更鲁棒):

// 原始规则数组
const rawPriceRules = [
  { id: 1, price: "20.0000", qty: "2.0000" },
  { id: 2, price: "15.0000", qty: "4.0000" },
  { id: 3, price: "10.0000", qty: "8.0000" }
];

// 预处理:转数值+升序排序
const priceRules = rawPriceRules
  .map(item => ({
    ...item,
    price: parseFloat(item.price),
    qty: parseFloat(item.qty)
  }))
  .sort((a, b) => a.qty - b.qty);

方案一:遍历匹配区间(直观易读)

通过扩展数组添加虚拟起始项,统一区间判断逻辑,代码清晰易懂:

function getMatchingPrice(inputQty) {
  const numQty = parseFloat(inputQty);
  
  // 处理无效输入
  if (isNaN(numQty) || numQty <= 0) {
    throw new Error("请输入有效的正整数/小数数量");
  }

  // 添加虚拟起始项,覆盖0 < 数量 ≤ 第一个qty的区间
  const extendedRules = [{ qty: 0 }, ...priceRules];

  // 遍历找到匹配的区间
  for (let i = 1; i < extendedRules.length; i++) {
    const prevQty = extendedRules[i-1].qty;
    const currentRule = extendedRules[i];
    if (numQty > prevQty && numQty <= currentRule.qty) {
      return currentRule.price;
    }
  }

  // 数量超过所有档位,返回最后一档价格
  return priceRules.at(-1).price;
}

方案二:函数式写法(简洁优雅)

用find方法实现,更符合现代JS风格:

function getMatchingPrice(inputQty) {
  const numQty = parseFloat(inputQty);
  
  if (isNaN(numQty) || numQty <= 0) {
    throw new Error("请输入有效的正整数/小数数量");
  }

  const extendedRules = [{ qty: 0 }, ...priceRules];
  
  // 找到匹配的规则项
  const matchedRule = extendedRules.slice(1).find((rule, index) => {
    const prevQty = extendedRules[index].qty;
    return numQty > prevQty && numQty <= rule.qty;
  });

  return matchedRule ? matchedRule.price : priceRules.at(-1).price;
}

测试验证

用你的示例测试,完全符合预期:

  • getMatchingPrice(2) → 返回20 ✔️
  • getMatchingPrice(3) → 返回15 ✔️
  • getMatchingPrice(5) → 返回10 ✔️
  • getMatchingPrice(9) → 返回10 ✔️

扩展说明

  • 如果你的规则数组可能动态变化,排序步骤能确保区间判断的正确性;
  • 可以根据需求调整超过最大数量的处理逻辑(比如抛出错误、返回自定义价格等);
  • 若需要保留价格的小数位数(比如四位),可以在返回时用toFixed(4)格式化。

内容的提问来源于stack exchange,提问作者Michel Janssen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:47:31