首页 > 解决方案 > 为什么这个 JS 函数返回数字是升序而不是降序?

问题描述

我是一名学习编码的学生,通过 freeCodeCamp 练习学习 JS。我在其中一个解释递归的练习中遇到了这个函数。从我看来合乎逻辑的情况来看,该函数应该将数字从 1 到 n 按降序排列在数组中,但在执行时,它会将数字按升序排列!为什么/如何发生?JS 是否以自上而下以外的方式执行它,或者我在这里遗漏了什么?

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(15));

从代码来看,代码似乎是这样做的:将常量 countArray 定义为 countup(n-1),然后将 n 添加为数组中的第一个元素。然后在 countup 运行时 (n-1) 添加 n-1 作为数组中的第二个元素,并且该过程不断重复。但在这种情况下,最终数组中的数字应该是 [n, n-1, n-2, .... , 3, 2, 1] 但实际结果是这个数组: [1,2,3, ...,n-2,n-1,n]。为什么/如何以这种方式发生,与它应该如何表现相反?

标签: javascriptrecursion

解决方案


您需要考虑递归调用期间会发生什么。也许这会有所帮助:

countup(3)
  - calls countup(2)
      - calls countup(1)
          - calls countup(0) - this returns [] right away
          - sets countArray to []
          - pushes 1 onto the array  <--- first number pushed
          - returns [1]
      - sets countArray to [1]
      - pushes 2 onto the array
      - returns [1,2]
  - sets countArray to [1,2]
  - pushes 3 onto the array
  - returns [1,2,3]           

如您所见,第一次将数字实际压入数组是当它下降到 1 时,然后堆栈展开添加每个连续的数字。


推荐阅读