尝试使用递归使我的斐波那契数列起作用,但遇到错误超出最大调用堆栈
。
代码:
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
正在记录正确的数字,但我仍然收到 maximum callstack
错误。
最佳答案
++
的行为在后缀和前缀表示法上是不同的。
来自 MDN :
If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.
这意味着您总是在递增 count
之前传递它,从而导致堆栈溢出。
要解决你的问题,改变
return genFib(count++, limit, pushFibNo(fibArray));
到
return genFib(++count, limit, pushFibNo(fibArray));
关于使用递归的 JavaScript 斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016580/