【问题标题】:Why is this returning undefined? (freecodecamp)为什么返回未定义? (免费代码营)
【发布时间】:2021-03-11 05:59:23
【问题描述】:

// Only change code below this line
var myArray = [];
function countdown(n){
  if (n < 1) {
    console.log('Finished array: ' + myArray);
    return myArray;
  } else {
    console.log('Pushing Value!');
    myArray.push(n)
    console.log('Calling function countdown');
    countdown(n - 1)
  }
}
console.log(countdown(10));
// Only change code above this line

代码感觉应该是正确的,但是函数返回undefined

我认为这与递归有关......

(规则:)

countdown(-1) should return an empty array.

countdown(10) should return [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

countdown(5) should return [5, 4, 3, 2, 1]
Passed

Your code should not rely on any kind of loops (for, while or higher order functions such as forEach, map, filter, and reduce).
Passed

You should use recursion to solve this problem.

【问题讨论】:

  • 您的else 案例没有返回声明。你的意思是return countdown(n - 1)

标签: javascript arrays recursion return


【解决方案1】:

递归是一种函数式遗产,因此将其与函数式风格一起使用会产生最佳效果。这意味着要避免诸如突变、在函数中间打印输出以及其他副作用之类的事情。这是你的程序重写后的样子 -

const countdown = (n = 0) =>
  n <= 0
    ? []
    : [ n, ...countdown(n - 1) ]
    
console.log(countdown(-1)) // []
console.log(countdown(10)) // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]

【讨论】:

    【解决方案2】:

    在缺少的 return 语句旁边

    // Only change code below this line
    var myArray = [];
    function countdown(n){
      if (n < 1) {
        console.log('Finished array: ' + myArray);
      } else {
        console.log('Pushing Value!');
        myArray.push(n)
        console.log('Calling function countdown');
        countdown(n - 1)
      }
        return myArray;
    }
    console.log(...countdown(10));

    您可以使用数组作为返回值,而无需使用全局变量。

    // Only change code below this line
    function countdown(n) {
        if (n < 1) return [];
        return [n, ...countdown(n - 1)];
    }
    
    console.log(...countdown(10));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-31
      • 2020-10-04
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多