[英]Max call stack exceeded
我了解超出的最大调用堆栈数。 但是,对于我的代码,是否有解决方法? 此外,在某个时刻,它最终将停止循环,即位置> counter1。
var a = 0;
var b = 1;
var c;
var counter1 = 1;
var position = 0;
window.onload = function() {
var position = prompt("Please enter the position number.","0");
calc1();
}
function calc1() {
if(position <= counter1) {
c = a+b;
counter1++;
calc2();
}
else {
callResult();
}
}
function calc2() {
if(position <= counter1) {
a = b+c;
counter1++;
calc3();
}
else {
callResult();
}
}
function calc3() {
if(position <= counter1) {
b = c+a;
counter1++;
calc1();
}
else {
callResult();
}
}
function callResult() {
if (position %3 == 1) {
document.getElementById("answer").innerHTML = a;
}
else if (position %3 == 2) {
document.getElementById("answer").innerHTML = b;
}
else {
document.getElementById("answer").innerHTML = c;
}
}
您应该避免递归并使用循环。 像这样:
window.onload = function() {
var position = prompt("Please enter the position number.","0");
maincalc();
}
function maincalc() {
var subcalc = [ calc1, calc2, calc3 ];
var calccount = 0;
while(position <= counter1) {
subcalc[ calccounter ]();
calccounter = (calccounter +1) % 3;
}
}
头寸的值一次给出,永远不变。
然后,您检查每个相互调用的calc1
, calc2
, calc3
if(position <= counter1)
:
calc1
> calc2
> calc3
> calc1
> ...
显然,这将继续进行,直到堆栈空间用完为止。
也许,如果您增加position
而不是counter1
或在位置大于计数器的情况下继续调用该问题,该问题将消失,即
if(position > counter1)
您可能需要退后一步,想一想您真正想要做什么。
据我了解,您正在计算斐波纳契数的总和?
看到这个Javascript Fibonacci答案,以了解如何更轻松地进行它并且无需任何递归调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.