如何在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
相关产品推荐
相关产品推荐

