简体   繁体   中英

Javascript Recursion?

I am practicing recursion. Conceptually I understand how this should work, (see below) but my code isn't working.

Please tell me what I am doing wrong. And please explain each step of your code and how it works. Clear Explanation is ten times better than just giving me code that works.

  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var buildList = function(value, length) {
    var result = [];
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};


buildList(0, 5);

I understand how recursion works on a conceptual level.

Your approach can't work, because the base case returns a new empty array, and other cases return the result of the recursion.

Instead, you should first recurse and then push

var buildList = function(value, length) {
  if (length <= 0) return [];
  var recur = buildList(value, length-1);
  recur.push(value);
  return recur;
};

Alternatively, in the base case you can avoid creating a new array

var buildList = function(value, length, array=[]) {
  if (length <= 0) return array;
  array.push(value);
  return buildList(value, length-1, array);
};

The problem is that with every call to your function, the result variable gets reinitialized to [] . If you declare that variable outside your function, the code works:

var result = [];
var buildList = function(value, length) {

   if(length === 0){
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};


buildList(0, 5);
console.log(result);
  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var result = []; //(1)

var buildList = function(value, length) {
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(value, length - 1);  //(2)

};


buildList(0, 5);

You're doing two things wrong:

  1. You're initializing result inside the method. This means every time the recursive method call is made, you're resetting result to an empty array.
  2. You're passing the array into the recursive call of buildlist(). You want to be passing the value in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM