You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何递归实现的countdown函数返回undefined?(FreeCodeCamp)

修复递归countdown函数返回undefined的问题

嘿,你猜得完全没错——问题根源就是递归调用的返回值处理,还有个容易忽略的全局变量坑。咱们拆解来看:

问题1:递归调用没有返回结果

你的else分支里确实调用了countdown(n - 1),但没把这个调用的结果return出去。举个例子,当n=10时,函数会执行push(10)然后调用countdown(9),但此时当前的countdown(10)函数并没有返回任何值,直到递归到n=0时才返回myArray,但这个结果没有被逐层传递回来,所以最外层的函数调用就会返回undefined。

问题2:全局数组导致的结果污染

你的myArray是全局变量,这意味着如果多次调用countdown函数(比如先调用countdown(5)再调用countdown(3)),之前的元素会保留在数组里,导致结果错误。比如第二次调用会得到[5,4,3,2,1,3,2,1],完全不符合题目要求。

修正后的代码方案

这里给你两种可行的修正方式,都满足题目要求的递归、无循环/高阶函数的限制:

方案1:用辅助函数传递数组(避免全局变量)

// Only change code below this line
function countdown(n){
  // 内部辅助函数,current是当前计数,arr是要构建的数组
  function buildCountdown(current, arr) {
    if (current < 1) {
      return arr;
    } else {
      arr.push(current);
      // 关键:递归调用时要return结果,让值逐层传递回去
      return buildCountdown(current - 1, arr);
    }
  }
  // 初始调用时传入空数组,保证每次调用都是独立的
  return buildCountdown(n, []);
}
// Only change code above this line

// 测试验证
console.log(countdown(-1)); // 输出 []
console.log(countdown(10)); // 输出 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
console.log(countdown(5)); // 输出 [5, 4, 3, 2, 1]

方案2:更简洁的递归写法(无辅助函数)

这种方式每次递归返回一个新数组,逻辑更直观:

// Only change code below this line
function countdown(n){
  if (n < 1) {
    return [];
  } else {
    // 先递归获取n-1的结果数组,再把n放到开头
    const result = countdown(n - 1);
    result.unshift(n);
    return result;
    // 也可以用concat写成一行:return [n].concat(countdown(n - 1));
  }
}
// Only change code above this line

验证所有测试用例

两种方案都能完美满足题目要求:

  • countdown(-1) 返回空数组
  • countdown(10) 返回[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
  • countdown(5) 返回[5, 4, 3, 2, 1]

内容的提问来源于stack exchange,提问作者user14420666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:37:39