javascript - 为什么这个 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]。为什么/如何以这种方式发生,与它应该如何表现相反?
解决方案
您需要考虑递归调用期间会发生什么。也许这会有所帮助:
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 时,然后堆栈展开添加每个连续的数字。
推荐阅读
- python - 如何从具有相同 x 值的多类标签生成二进制向量
- paypal - 多次加载 Paypal 结帐按钮
- mysql - 使用 union all 时操作“concat”的排序规则的非法混合
- android - 如果我发布的库使用 AndroidX 但使用它的应用程序不是,有什么问题吗?
- hyperledger-fabric - 当网络出现故障时,所有 Hyperledger Fabric (v 1.4.2) 对等点都会崩溃
- sql - 根据每个项目的最新交易日期选择数据
- powerbi - 如何将 Excel 转换为 DAX 公式?
- c# - 使用正则表达式分组结构匹配部分字符串
- spring-boot - MockMvc 保持为空
- javascript - 如何在 sequelize findAll 中包含特定关联?