Node.js递归函数问题:BytesBoleto导出PDF文件名索引未递增
问题分析与修复
核心问题
递归函数中使用的findex是数字类型(基本类型),在JavaScript中基本类型按值传递。每次递归调用时传递的是findex的副本,递归内部修改副本的值不会影响外层函数的findex变量,导致所有文件都复用第一次递增后的索引值(始终为1)。
修复方案
提供两种可行的解决方式:
方案1:用引用类型存储索引(推荐)
将索引存入对象中,对象属于引用类型,递归时修改对象的属性会同步到所有引用该对象的位置:
function JsontoBase64 (jsonData, filename) { if (typeof jsonData !== 'object' || jsonData === null) { throw new Error("无效输入:必须是JSON对象。"); } // 用对象存储索引,确保递归中索引状态共享 const indexHolder = { value: 0 }; function procurarBytesBoleto(obj, fname) { for (const key in obj) { if (obj.hasOwnProperty(key)) { if (key === 'BytesBoleto' && typeof obj[key] === 'string') { indexHolder.value += 1; Base64toPDFandSave(obj[key], `${fname}${indexHolder.value}.pdf`); } else if (typeof obj[key] === 'object') { procurarBytesBoleto(obj[key], fname); } } } } procurarBytesBoleto(jsonData, filename); }
方案2:让递归函数返回更新后的索引
每次递归调用结束后,将更新后的索引返回给外层函数,外层用返回值更新自身的索引变量:
function JsontoBase64 (jsonData, filename) { if (typeof jsonData !== 'object' || jsonData === null) { throw new Error("无效输入:必须是JSON对象。"); } function procurarBytesBoleto(obj, fname, findex) { let currentIndex = findex; for (const key in obj) { if (obj.hasOwnProperty(key)) { if (key === 'BytesBoleto' && typeof obj[key] === 'string') { currentIndex += 1; Base64toPDFandSave(obj[key], `${fname}${currentIndex}.pdf`); } else if (typeof obj[key] === 'object') { // 接收递归返回的更新后索引 currentIndex = procurarBytesBoleto(obj[key], fname, currentIndex); } } } // 将更新后的索引返回给外层 return currentIndex; } procurarBytesBoleto(jsonData, filename, 0); }
额外优化提示
- 模块导入语句(
require('fs')、require('path')等)建议放在文件顶部,避免函数每次调用时重复导入 - 可移除冗余的
console.log语句,减少输出干扰 - 考虑使用
fs.promises.writeFile结合async/await,提升异步代码的可读性与可控性
内容的提问来源于stack exchange,提问作者Mr Papiro
相关产品推荐
相关产品推荐

