简体   繁体   中英

why isn't recursion working? i am trying to display n to 1 series

Javascript Recursion


why isn't recursion working here? i see coundown(n-1); isn't working for some reason. I want to display [5,4,3,2,1]

   function countdown(n){
    if (n<1){
    return [];

   } else {

    var myArr = [];
    myArr.push(n);
    countdown(n-1);
    return myArr;

   }
  }
  countdown(5);

Your code creates a new array at every recursive call, puts one value in it and returns it. Nothing is done with the array that is returned, as each execution instance of your function seems only interested in its own array, which it returns.

You need to create one array, and extend that while backtracking out of recursion, each time making sure you capture the array that the recursive call gives you back as return value:

 function countdown(n) { if (n < 1) { // This is the only time you should create an array: return []; } else { // Get the array that comes out of recursion! let myArr = countdown(n-1); // Prefix the current value into it myArr.unshift(n); // And pass that extended array further up // the recursion tree: return myArr; } } console.log(countdown(5));

Written a bit more concise it could become:

 const countdown = (n) => n < 1 ? [] : [n].concat(countdown(n-1)); console.log(countdown(5));

And without recursion:

 const countdown = (n) => Array.from({length: n}, (_, i) => n - i); console.log(countdown(5));

var myArr =[];
    function clearandcountdown(n)
    {
        myArr = [];   // clearing the array each time when the function called
        return countdown(n);   // calling the recursion function
    }
    function countdown(n){

        if (n<1)
        {
            return []
        }
        else
        {
            myArr.push(n);
            countdown(n-1);
        }
        return myArr;
    }
  document.write(clearandcountdown(5));

You must use this code here you created myArr inside the else statement and you are setting it to empty for every function call here I used one extra function to clear the array each time when you call the function. Hope this will clear your doubts. Thank You :)

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