使用递归的JavaScript斐波那契 [英] JavaScript fibonacci using recursion
问题描述
尝试使用递归使我的斐波那契数列起作用,但遇到错误最大调用堆栈超出
.
Trying to get my fibonacci sequence to work using recursion but am running into the error maximum callstack exceeded
.
代码:
var genFib = function(count, limit, fibArray) {
if (count === undefined || count === null) {
var count = 0;
}
if (fibArray === undefined || fibArray === null) {
var fibArray = [0, 1];
}
if (count === limit) {
console.log(fibArray);
return fibArray;
}
var pushFibNo = function(fibArray) {
fibArray.push(fibArray[fibArray.length - 1] + fibArray[fibArray.length - 2]);
return fibArray;
};
// console.log(count++);
// console.log(limit);
// console.log(pushFibNo(fibArray));
return genFib(count++, limit, pushFibNo(fibArray));
};
genFib(null, 50, null);
底部的三个 console.logs
正在注销正确的号码,但我仍然遇到最大调用堆栈
错误.
The three console.logs
towards the bottom are logging out correct numbers, but I'm still getting the maximum callstack
error.
推荐答案
++
的行为在后缀和前缀表示法中有所不同.
The behaviour of ++
is different in postfix and prefix notation.
来自 MDN :
如果使用后缀,则在操作数后加上运算符(例如x ++),则它会在递增之前返回该值.
If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
如果在操作数前使用带前缀的运算符(例如++ x),则它将在递增后返回该值.
If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.
这意味着您总是在递增 count
之前传递它,从而导致堆栈溢出.
This means that you are always passing count
before incrementing it, resulting in stack overflow.
要解决您的问题,请更改
To solve your problem, change
return genFib(count++, limit, pushFibNo(fibArray));
收件人
return genFib(++count, limit, pushFibNo(fibArray));
这篇关于使用递归的JavaScript斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!