Skip to content Skip to sidebar Skip to footer

Javascript Recursion Completes Before Traversing The Whole Tree?

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 fileData = { dir : 'ap

Solution 1:

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;
}

Post a Comment for "Javascript Recursion Completes Before Traversing The Whole Tree?"