有人可以直观地解释这里发生了什么吗?
var stack = [];
function countDown(int) {
stack.push(int);
if (int === 1) {
return 1;
}
return countDown(int - 1);
}
function multiplyEach() {
// Remove the last value of the stack
// and assign it to the variable int
int = stack.pop();
x = stack.length;
// Base case
if (x === 0) {
return int;
}
// Recursive case
else {
stack[x - 1] = int * stack[x - 1];
return multiplyEach();
}
}
//调用函数
countDown(7);
//然后打印出multiplyEach()返回的值
console.log(multiplyEach());
我有点明白,它正在创建一个堆栈,并将所有内容相乘,但我无法想象它。
然后:
Stack[x-1] is getting me
最佳答案
这是一个由两部分组成的算法。
首先 countDown(n)
用从 n
到 1
的值填充数组 stack
,因此 堆栈 = [n, n-1, n-2, ..., 3, 2, 1]
。 countDown
的返回值从未被使用,因此可以忽略 return
语句。唯一重要的是它按照解释填充了 stack
数组。
其次,multiplyEach
重复获取堆栈的最后一个元素,将其删除,并将其与数组中的下一个最后一个元素相乘:
[n, n-1, n-2, ..., 6, 5, 4, 3, 2, 1]
[n, n-1, n-2, ..., 6, 5, 4, 3, 2]
[n, n-1, n-2, ..., 6, 5, 4, 6]
[n, n-1, n-2, ..., 6, 5, 24]
[n, n-1, n-2, ..., 6, 120]
...
[n!]
换句话说,该算法计算提供给 countDown
的数字 n
的阶乘。
关于javascript - 另一个 JavaScript 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9993420/