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

使用JavaScript编写的订单计算程序报Cannot read property 'push'错误修复

咖啡点单找零工具报错修复指南

报错直接原因

原代码中voidList[i].push(...)的写法存在逻辑错误:

  • voidList初始为空数组,索引为0、1、2...的位置没有预先定义为数组类型,读取voidList[i]得到的是undefined,对undefined调用push方法,就会触发Uncaught TypeError: Cannot read property 'push' of undefined报错。

附带存在的其他问题

  • 计算每个面额的找零数量时没有取整,会出现非整数的纸币/硬币计数,扣减找零总金额时会出现浮点计算误差
  • 付款金额不足时直接递归调用init(),没有清空旧的找零记录,重复流程时会残留历史数据
  • 没有处理找零为0、用户输入空值/非数字的场景,容易出现输出undefined或者计算结果为NaN的问题

核心修复逻辑

  • 取消嵌套数组的错误设计,直接给找零数量数组的对应索引赋值,每次计算前先清空数组旧值
  • 计算面额数量时用Math.floor()向下取整,保证计数为整数
  • 所有用户输入增加合法性校验,非法输入时给出明确提示再重走流程
  • 找零为0时直接输出对应提示,不渲染空的找零明细

修复后完整代码

业务逻辑JS代码

const americanoPrice = 3000;
const lattePrice = 5000;
const iceChocolatePrice = 500;
// 可找零的面额列表
const changeDenominations = [1000, 500, 100, 50, 10];
// 存储每个面额对应的找零数量
let changeCountList = [];
let totalCost = 0;
let remainChange = 0;

// 获取用户点单信息
function getOrder() {
  const americanoNum = Number(prompt("请输入美式咖啡购买数量"));
  const latteNum = Number(prompt("请输入拿铁购买数量"));
  const iceChocolateNum = Number(prompt("请输入冰巧克力购买数量"));
  // 校验输入是否为有效非负数字
  const isInputValid = [americanoNum, latteNum, iceChocolateNum].every(num => !isNaN(num) && num >= 0);
  if (!isInputValid) {
    alert("点单数量输入无效,请输入大于等于0的数字");
    return false;
  }
  totalCost = americanoNum * americanoPrice + latteNum * lattePrice + iceChocolateNum * iceChocolatePrice;
  return true;
}

// 计算找零明细
function calcChange(payAmount) {
  changeCountList = [];
  remainChange = payAmount - totalCost;
  if (remainChange < 0) {
    alert(`付款金额不足,还差${Math.abs(remainChange)}元`);
    return false;
  }
  if (remainChange === 0) return true;

  for (let i = 0; i < changeDenominations.length; i++) {
    // 向下取整得到当前面额的最大可用数量
    const denominationCount = Math.floor(remainChange / changeDenominations[i]);
    changeCountList[i] = denominationCount;
    // 扣减当前面额对应的总金额
    remainChange = remainChange - denominationCount * changeDenominations[i];
  }
  return true;
}

// 渲染结果到页面
function renderResult() {
  document.write(`<p>订单总金额:${totalCost} 韩元</p>`);
  if (remainChange === 0) {
    document.write("<p>付款金额恰好匹配,无需找零</p>");
    return;
  }
  document.write("<p>找零明细:</p>");
  for (let i = 0; i < changeDenominations.length; i++) {
    const count = changeCountList[i] || 0;
    // 仅展示数量大于0的面额
    if (count > 0) {
      document.write(`<p>${changeDenominations[i]} 面额:${count} 张/枚</p>`);
    }
  }
}

// 主流程入口
function init() {
  const orderValid = getOrder();
  if (!orderValid) {
    init();
    return;
  }
  const payAmount = Number(prompt("请输入付款金额"));
  if (isNaN(payAmount) || payAmount < 0) {
    alert("付款金额输入无效,请输入大于等于0的数字");
    init();
    return;
  }
  const changeValid = calcChange(payAmount);
  if (!changeValid) {
    init();
    return;
  }
  renderResult();
}

init();

页面HTML代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>咖啡点单找零计算工具</title>
</head>
<body>
  
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 07:36:00