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

基于select下拉框的计算器返回NaN,无控制台报错如何排查?

问题根源

  • 平均票价下拉框值非法:从8元档位开始的option,value设置为string:$X格式,不是可参与运算的数字,运算直接返回NaN
  • 事件绑定范围错误:document.querySelector("select")仅会匹配页面第一个下拉框,其余三个下拉框修改后不会触发重新计算逻辑
  • 销售额计算逻辑错误:计算销售额时读取了DOM中customers_result的初始值,该值自带千位分隔符逗号,无法转为合法数字参与运算,应直接使用本次计算得到的客户数变量

修复代码

替换原有JS逻辑即可:

// 给所有下拉框绑定change事件
document.querySelectorAll("select").forEach(item => {
  item.addEventListener('change', recalculate)
})

// 页面加载完成先执行一次计算,保证初始值匹配
window.addEventListener('load', recalculate)

function recalculate() {
  // 所有参数统一转为数字类型
  const locations = Number(document.getElementById('locations').value)
  // 处理平均票价的非法值,提取数字部分
  let averagePrice = document.getElementById('average_price').value
  averagePrice = Number(averagePrice.replace('string:$', ''))
  const donationRate = Number(document.getElementById('donation_rate').value)
  const customersNum = Number(document.getElementById('customers_number').value)
  const weeksInYear = 52

  // 先计算所有结果,再写入DOM
  const customersResult = locations * weeksInYear * customersNum
  const donationsResult = donationRate * customersNum * locations * averagePrice
  const salesResult = locations * customersNum * weeksInYear * averagePrice

  // 写入DOM并保留原有格式:千位分隔符、货币符号
  document.getElementById('customers_result').innerHTML = customersResult.toLocaleString()
  document.getElementById('donations_result').innerHTML = `$${donationsResult.toLocaleString('en-US', {maximumFractionDigits: 0})}`
  document.getElementById('sales_result').innerHTML = `$${salesResult.toLocaleString('en-US', {maximumFractionDigits: 0})}`
}

优化建议

直接修改average_price下拉框的option值,把所有string:$X格式的value改成纯数字(比如<option label="$8" value="8">$8</option>),就可以去掉代码中averagePrice.replace的兼容处理逻辑,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:06:03