[英]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.