2015-10-22 13 views
2

我想試用遞歸計算複合興趣而不是循環。在Ruby和JS中寫了相同的函數,但Ruby的工作原理是JS,但是JS未定義

在Ruby:

def compound balance, percentage 
    balance + percentage/100 * balance 
end 

def invest amount, years, rate 
    return amount if years == 0 
    invest compound(amount, rate), years - 1, rate 
end 

這工作得很好。 1年後5%的1萬美元是10,500美元; 10年後,16,288美元。

現在JavaScript中的邏輯相同(ES6)。

function compound(balance, percentage) { 
    return balance + percentage/100 * balance; 
} 

function invest(amount, years, rate) { 
    if (years === 0) { 
     return amount; 
    } else { 
     invest(compound(amount, 5), years - 1, rate); 
    } 
} 

這返回undefined,但我不明白爲什麼。它使用正確的參數調用invest正確的次數,並且邏輯相同。 compound函數起作用,我分別測試了它。那麼......有什麼可能是錯的?

回答

5

如果逐步代碼「脫離」函數的結尾,Ruby函數會自動返回最後一個表達式的值。 JavaScript的(以及大多數其他編程語言)做到這一點,所以你需要將else子句中返回值明確:

function invest(amount, years, rate) { 
    if (years === 0) { 
     return amount; 
    } else { 
     return invest(compound(amount, 5), years - 1, rate); 
    } 
} 

或使用條件運算符:

function invest(amount, years, rate) { 
    return years === 0 ? amount : invest(compound(amount, 5), years - 1, rate); 
} 
+0

唉唉,解決它。這次真是萬分感謝。我知道JS缺乏隱式返回,但我認爲最終的「返回量」將從整個遞歸調用序列中返回。我想它只是返回到調用它的堆棧框架? – GreenTriangle

相關問題