2015-06-12 215 views
0

爲什麼下面的方法總是返回undefined?事件雖然控制檯中的日誌顯示爲真?
javascript中的遞歸方法總是返回undefined而不是true,

var x = [1,2,3,4,5]; 
var y = 9; 


function addUp (x, y) { 
    for (var i=0, j=1; j < x.length; j++) { 
    if (x[i] + x[j] === y) { 
     console.log("in here result should be true"); 
     var result = true; 
     break; 
    } 
    } 

    console.log("len", x.length, "result",result); 
    if ((!result) && (x.length > 2)) { 
    console.log("recursively calling"); 
    addUp(x.slice(i+1, x.length), y) 
    } else if(result) { 
    console.log("in the if why doesn't this return true?") 
    return true; 
    } else { 
    return false; 
    } 
} 

addUp(x,y); 

回答

2

你可能想回報遞歸調用的結果:

return addUp(x.slice(i+1, x.length), y) 

,而不只是:

addUp(x.slice(i+1, x.length), y) 
+0

衛生署!確實總是錯過了,謝謝@shomz!一旦stackoverflow允許我在5分鐘內將問題標記爲正確。 – climboid

+1

不客氣,它發生了。 :)有一件事我學到了,幫助我避免了這個錯誤:在編寫遞歸函數時,首先編寫基本案例(可以是'if(x.length <= 2)return !! result;' )和遞歸大小寫('return addUp ...'),然後處理代碼體。 – Shomz

0

的問題是在你的第一個if聲明

console.log("len", x.length, "result",result); 
    if ((!result) && (x.length > 2)) { 
    console.log("recursively calling"); 
    addUp(x.slice(i+1, x.length), y) 
    } else if(result) { 
    console.log("in the if why doesn't this return true?") 
    return true; 
    } else { 
    return false; 
    } 

您將看到if ((!result) && (x.length > 2)) {不返回任何內容。因此,如果發現這個匹配,下面的兩個else語句將不會被執行。

您應該在第一個if語句中提供return語句,或者在方法結尾處提供最終返回值。

相關問題