Javascript recursion completes before traversing the whole tree?

后端 未结 1 689
礼貌的吻别
礼貌的吻别 2021-01-21 18:28

I\'m working on a project where one exercise asks to traverse a data structure below and returning an array containing all the files (i.e. *.js, *.css):

var file         


        
相关标签:
1条回答
  • 2021-01-21 18:57

    You need to make the files variable local to the recursive function. Otherwise, when you recurse, you're overwriting the value used in the caller.

    function listFiles(data) {
      var retval = [];
    
      (function crawl(filedata) {
        var files = filedata.files;
    
        if (typeof files !== 'undefined') {
          for (var i = 0; i < files.length; i++) {
            if (typeof files[i] === 'string') {
              retval.push(files[i]);
            } else {
              crawl(files[i]);
            }
          }
        }
      })(data);
    
      return retval;
    }
    
    0 讨论(0)
提交回复
热议问题