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

如何在JavaScript函数内部调用自身?递归调用action函数失效求助

问题原因

代码存在4个问题,直接导致递归调用时抛出异常、逻辑中断:

  • 递归调用时id变量未赋值
    传入type="start2"触发递归时,if (type != "start2")分支不会执行,id没有被赋值为有效值,默认是undefined,后续调用id.trim()会直接抛出JS异常,中断代码执行。
  • 空值判断逻辑错误
    if (id.trim() != null || id.trim() != "")使用了逻辑或||,该条件永远为真:哪怕id是空串,id.trim() != null的结果也为真,永远不会触发空值提示分支,空值场景下后续逻辑必然报错。
  • AJAX操作写在判断分支外
    xhttp.setRequestHeader和xhttp.send方法写在了id合法性判断的分支外部,当id为空时,xhttp未初始化,直接调用方法会抛出未定义错误。
  • 参数冗余重复声明
    函数参数order、type已经被声明,函数内部再次用var声明属于冗余写法,虽然不会直接报错,但容易引发变量作用域混淆。

修复后代码

// 新增可选参数originId,递归调用时传入已获取的id,避免二次弹窗
function action(order, type, originId) {
  let xhttp;
  let id;
  // 避免和参数名冲突,重命名为orderText
  const orderText = document.getElementById(order).innerText;

  if (type !== "start2") {
    id = prompt("Načtěte svůj QR kód.");
  } else {
    // 递归场景直接使用之前传入的id
    id = originId;
  }

  // 修正空值判断逻辑,先判断id存在再调用trim,使用逻辑与&&
  if (id && id.trim() !== null && id.trim() !== "") {
    xhttp = new XMLHttpRequest();
    xhttp.open("POST", "functionSmallCustomers.php", true);
    xhttp.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        const str = this.responseText.trim();
        if (str === '1') {
          location.reload();
        } else if (str === '2') {
          const result = confirm("Opravdu chcete pikovat další zakázku? Jednu už máte rozpikovanou.");
          if (result) {
            // 递归时传入当前已获取的id
            action(order, "start2", id);
          }
        } else {
          alert(str);
        }
      }
    };
    // AJAX配置和发送移到判断分支内部,仅id合法时执行
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(`type=${type}&o=${orderText}&i=${id}`);
  } else {
    alert("Nenačetli jste QR kód.");
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:45:03