【发布时间】:2023-03-27 03:21:01
【问题描述】:
我希望这不是一个重复的问题——尽管我在这方面找不到太多帮助。
我正在练习递归函数(我是新手),我正在尝试将数组中的每个数字相乘。有点像阶乘。我有这段代码,但它只返回undefined 结果。
代码如下:
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;
}
// Recursive case
else {
stack[int - 1] = int * stack[x - 1];
return multiplyEach(int);
}
}
// Call the function countDown(7)
countDown(7);
// And then print out the value returned by multiplyEach()
console.log(multiplyEach());
非常感谢您提供任何见解。
干杯!
【问题讨论】:
-
首先,不要使用全局状态为
var stack。而且你也不应该使用自己的堆栈结构,除非你必须(见我的answer)
标签: javascript arrays recursion