如何在递归javascript调用中正确设置return语句?

问题描述

我正在尝试通读目录结构和子目录,以查找名称与一组条件匹配的文件。我正在使用递归函数遍历目录中的每个项目。如果它是文件且符合条件,则返回文件路径,否则,移至下一项。

我可以在找到匹配项时记录该匹配项,但是在尝试从该函数返回时得到未定义状态。

许多诸如herehere之类的帖子都表明我需要在递归调用添加return语句,但似乎无法正确执行。

如何从此函数返回?

function checkForProjectTrackFile(projfolder,projname) {

  fs.readdirsync(projfolder).forEach(projfile => {

    if (fs.statSync(path.join(projfolder,projfile)).isDirectory()) {

      //if a directory,call function again
      return checkForProjectTrackFile(path.join(projfolder,projfile),projname)
      
    } else {
        
        if (isProjectTrackMatch(projfile,projname)) {
          
          console.log("Match Found",path.join(projfolder,projfile))
          
          //match criteria met,return the file path  => UNDEFINED

          return (path.join(projfolder,projfile))
        }
    }
 })
}

解决方法

每次通过checkForProjectTrackFile()时,您都需要返回一个值,该值指示您找到了结果(在这种情况下为字符串),或者一个值指示未找到任何结果(我选择了null):

function checkForProjectTrackFile(projfolder,projname) {
  let r = null; // assume

  fs.readdirSync(projfolder).forEach(projfile => {

    if (fs.statSync(path.join(projfolder,projfile)).isDirectory()) {

      //if a directory,call function again
      r = checkForProjectTrackFile(path.join(projfolder,projfile),projname)
      if ( r !== null ) {
         break; // Found a match,so unwind and get out
         // Note: return r would also work here
      } // no need for 'else' since we want to keep looping to check the rest of the projfile values at this level!
      
    } else {
      if (isProjectTrackMatch(projfile,projname)) {
          
        console.log("Match Found",path.join(projfolder,projfile))
          
        //match criteria met,return the file path  => UNDEFINED

        r = (path.join(projfolder,projfile));

        break; // We found a match,so stop processing directory entries
      }
    }
  })

  return r; // Return what we found (whether null or otherwise)
}