[英]I am trying to understand why this JS snippet isn't working, could use some guidance adding to WP
[英]why isn't recursion working? i am trying to display n to 1 series
为什么递归在这里不起作用? 我看到倒计时(n-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);
您的代码在每次递归调用时创建一个新数组,将一个值放入其中并返回它。 返回的数组没有做任何事情,因为函数的每个执行实例似乎只对它自己的数组感兴趣,它返回。
您需要创建一个数组,并在从递归回溯的同时扩展它,每次确保捕获递归调用返回的数组作为返回值:
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));
写得更简洁一点,它可以变成:
const countdown = (n) => n < 1 ? [] : [n].concat(countdown(n-1)); console.log(countdown(5));
并且没有递归:
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));
您必须在此处使用此代码,您在 else 语句中创建了 myArr 并且您在此处为每个函数调用将其设置为空,每次调用该函数时,我都使用了一个额外的函数来清除数组。 希望这会消除您的疑虑。 谢谢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.