使用递归函数进行两次倒计时



我试图在不使用全局变量的情况下使用JavaScript编写递归,但我不确定该程序是否可以像愿望输出一样实现。

问题是";给定一个非负整数n,在输出中创建一个双倒计时模式"示例:如果你运行doubleCountdown(5(,你也会得到以下输出:

5
4
3
2
1
4
3
2
1
0

我尝试了以下方法:通过这种方式,可以从下到上输出,但不能精确输出:

double_countdown(5);
function double_countdown(n){
if(n == 0){
console.log(n);
return
}
console.log(n);
double_countdown(n-1);
console.log(n);
}

通过这种方式,我使用了global作为期望的输出,但不是标准的方式。

let second_n = 0;
let double_count =0;
double_countdown(5);
function double_countdown(n){
if(n == 0 && double_count == 0){
double_count = 1;
double_countdown(second_n-1);
console.log(n);
}
if(n == 0){
return
}else{
second_n +=1;
}
console.log(n);
double_countdown(n-1);
}

我会把单个倒计时写成一个递归函数,而双倒计时函数只需调用两次。这样可以使所有部分保持简单。

const countdown = (s, e = 0) => 
s < e ? [] : [s, ...countdown (s -1, e)]
const doubleCountdown = (n) => 
[...countdown (n, 1), ...countdown (n - 1, 0)]
console .log (doubleCountdown (5))

然后,你可以在作业中记录你想要的答案。也许类似for (let n of doubleCountdown (5)) {console .log (n)}

通过提供和使用比所需的第一个参数(即当前倒计时值(更多的参数来实现递归函数,从而跟踪其递归状态。

因此,可以实现例如能够运行倒计数周期CCD_ 2次的功能。并且CCD_ 3和CCD_。

function countDownNTimes(value = 0, times = 1, initialValue) {
// initially invoked with an `undefined` value for `initialValue`.
initialValue ??= value;
console.log(value);
if (times >= 2) {
if (value <= 1) {
// does trigger a new recursion cycle with minimized boundaries.
countDownNTimes(initialValue - 1, --times, initialValue);
} else {
// stays within the current recursion of minimized boundaries.
countDownNTimes(--value, times, initialValue);
}
} else if ((times >= 1) && (value >= 1))  {
// stays within the current, final recursion of reastablished boundaries.
countDownNTimes(--value, times, initialValue);
}
}
const countDownTwice = value => countDownNTimes(value, 2);
console.log('... countDownTwice(5) ...');
countDownTwice(5);
console.log('... countDownNTimes(3, 3) ...');
countDownNTimes(3, 3);
.as-console-wrapper { min-height: 100%!important; top: 0; }

最后,经过多次尝试。我得到了答案。如果有任何问题,请帮助改进。

double_countdown(5);
function double_countdown(n,sc=0){
if(sc == 0) sc = n;
if(n == 0 ) return ;
console.log(n);
double_countdown(n-1,sc);
console.log(sc-n);
}

最新更新