2016-11-16 109 views
-1

有人可以向我解釋爲什麼這個遞歸函數不返回時退出。提前致謝。Javascript函數不返回/退出

var numberArr = [5,4,3,2]; 
 

 
function findCommon(x) {  
 
    x += numberArr[0]; 
 
    for (var i = 1; i < numberArr.length; i++) { 
 
    if((x % numberArr[i]) === 0) { 
 
     continue; 
 
    } else { 
 
     findCommon(x); 
 
    }  
 
    } 
 
    console.log("done " + x); 
 
    return x; 
 
} 
 

 
findCommon(0);

+3

我不清楚你的意思是「不退回」。 –

+2

這將運行到無限循環...你總是隻比較第一個元素 – Geeky

+0

什麼是你的基礎條件...直到當你想運行它 – Geeky

回答

0

嘗試abouve代碼..它是如此棘手的正在發生的事情在你的代碼。實際上你的函數findcommon(x)正在調用自己,發生了什麼事情,它運行當前的函數和調用的函數。這意味着如果我們撥打findcommon(x)一次,那麼它不會從目前的突破不會結束。它逐個完成兩個功能。

var numberArr = [5,4,3,2]; 

function findCommon(x) {  
    x += numberArr[0]; 
    for (var i = 1; i < numberArr.length; i++) 
    { 
    if((x % numberArr[i]) === 0) 
    { 
     continue; 
    } 
    else 
    { 
     findCommon(x); 
    }  
    } 
    console.log("done " + x); 
    return x; 
} 
//findCommon(3); 
console.log("done " +findCommon(3)); 

例如:如果我從函數的調用函數B將完成兩個B和A 喜歡你的函數findCommon(X);自稱這麼多次。這就是爲什麼它在recursive.hope它有幫助。

0

您的代碼不會退出的回報,因爲你可以看到,如果你修改它稍微向您展示一些更多的信息。

var numberArr = [5,4,3,2]; 
 

 
function findCommon(x) {  
 
    x += numberArr[0]; 
 
    for (var i = 1; i < numberArr.length; i++) { 
 
    if((x % numberArr[i]) === 0) { 
 
     console.log("Continuing: " + i) 
 
     continue; 
 
    } else { 
 
     console.log("B: " + findCommon(x)) 
 
    }  
 
    } 
 
    console.log("done " + x); 
 
    return x; 
 
} 
 

 
console.log("A: " + findCommon(0));

+0

在我的控制檯登錄「完成60」之後,它應該點擊「return x」並終止,但它一直在繼續。 – Yas

0

我achived我的目的與下面的代碼。關於如何避免返回全局變量或其他方式我可以做到這一點的任何建議。

var numberArr = [5,4,3,2]; 
 
var y; 
 

 
function findCommon(x) {  
 
    x += numberArr[0]; 
 
    for (var i = 1; i < numberArr.length; i++) { 
 
    if((x % numberArr[i]) === 0) { 
 
     console.log("continue " + x); 
 
     continue; 
 
    } else { 
 
     console.log("not div " + x); 
 
     findCommon(x); 
 
     return y; 
 
    }  
 
    } 
 
    y = x; 
 
    console.log("done " + x); 
 
} 
 

 
findCommon(0);