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

如何在不影响其他函数的前提下,避免空值/0值触发折扣计算

解决折扣计算逻辑问题:空/0值时不应用折扣

当前代码在「Deadline (months)」输入框为空或值为0时,会默认应用20%折扣,需要调整为这种情况跳过折扣计算。以下是修改方案:

关键修改点

  • 优化months参数的解析逻辑,处理空值和0的情况
  • 调整getDiscountPercent函数,当months为0、空或无效值时返回0(无折扣)

修改后的完整代码

//Dropdown list calculation//
var service_prices = new Array();
service_prices["0"] = 0;
service_prices["1500"] = 1500;
service_prices["4000"] = 4000;
service_prices["8000"] = 8000;

//^gives me value of each drop down list item
function getServicePrice() {
  var serviceOptionPrice = 0;
  var form = document.forms["formulario"];
  var selectedOption = form.querySelector("#servicePrice");
  if (service_prices[selectedOption.value]) {
    serviceOptionPrice = service_prices[selectedOption.value];
  }
  return serviceOptionPrice;
}

//checkbox calculation//
function extraPrices() {
  var extraPrices = 0;
  var form = document.forms["formulario"];
  var selectedBoxes = form.querySelectorAll("#selectedBox");
  selectedBoxes.forEach(box => {
    if (box.checked == true) {
      extraPrices += 400;
    }
  })
  //returns me value of each marked checkbox (all of them == 400)
  return extraPrices;
}

//Calculate how much is going to be removed from the final Value
const getDiscountPercent = months => {
  // 当months为0、空或无效值时,返回0(无折扣)
  if (!months || months <= 0) return 0;
  return months < 4 ? months * 0.05 : 0.2;
};

const getTotal = (servicePrice, extraPrice, months) => {
  const subtotal = servicePrice + extraPrice;
  const discountPercent = getDiscountPercent(months);
  return subtotal - (subtotal * discountPercent);
};

//Returns me what's gonna be subtracted from final value
function Total() {
  // 解析输入值,空值或非数字会转为NaN
  var months = parseInt(document.querySelector('#months').value);
  // 处理NaN的情况,转为0
  months = isNaN(months) ? 0 : months;
  
  var subtotal = getServicePrice() + extraPrices();
  var totalFinal = subtotal - (subtotal * getDiscountPercent(months));
  document.getElementById("result").value = "€" + totalFinal ;
}
// 注意:totalFinal是Total函数内部变量,外部无法直接访问,这里会报错,建议移除或放在函数内
// console.log(totalFinal)

修改说明

  1. getDiscountPercent函数:新增判断逻辑,当months为0、空值或无效值时直接返回0,确保无折扣应用。
  2. Total函数:
    • 处理parseInt解析空字符串得到NaN的问题,将NaN转为0
    • 简化计算逻辑,先计算小计,再应用折扣
    • 移除了外部无法访问的console.log(totalFinal),避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:35:30