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

JS递归函数未自增自身参数 重复打印首份PDF且无法停止问题

问题根因

  • 后自增运算符逻辑错误:index++属于后自增,执行时会先返回index的当前原始值,再对变量本身做自增运算。因此printDocuments(index++)实际传入的始终是自增前的旧index值,导致每次都打印同一份文档,递归永远无法推进到下一个下标。
  • 递归终止条件越界:数组合法下标范围是0 ~ documentURLs.length - 1,原有判断index > documentURLs.length才终止,会导致index等于数组长度时依然尝试访问不存在的数组元素,出现逻辑异常。

修复方案

修改两个问题点即可,修复后代码如下:

JavaScript代码

var documentURLs = ["maca.pdf", "maca2.pdf"]
function printDocuments(index){
   // 修正终止条件:下标等于数组长度时直接终止,避免越界
   if(index >= documentURLs.length){
        return;
   }
   printJS({
     printable: documentURLs[index],
     type: 'pdf',
     onPrintDialogClose: function () {
       console.log(index);
       // 直接传index+1作为下一次调用的参数,避免自增运算符的歧义问题
       printDocuments(index + 1)
     }
   })
}

HTML代码(无变动)

<button type="button" onclick="printDocuments(0)">Print</button>

如果偏好使用自增运算符,也可以把index++换成前自增++index,前自增会先对变量做自增,再返回自增后的值,也能解决参数传递问题,但直接使用index + 1可读性更强,不容易出现理解歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:06:01