[英]why isn't recursion working? i am trying to display n to 1 series
why isn't recursion working here?为什么递归在这里不起作用? i see coundown(n-1);
我看到倒计时(n-1); isn't working for some reason.
由于某种原因无法正常工作。 I want to display [5,4,3,2,1]
我想显示 [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.您必须在此处使用此代码,您在 else 语句中创建了 myArr 并且您在此处为每个函数调用将其设置为空,每次调用该函数时,我都使用了一个额外的函数来清除数组。 Hope this will clear your doubts.
希望这会消除您的疑虑。 Thank You :)
谢谢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.