2012-10-05 297 views
1

我有一個計算稅款的函數。遞歸函數返回undefined

function taxes(tax, taxWage) 
{ 
    var minWage = firstTier; //defined as a global variable which is not 2299. 
    if (taxWage > minWage) 
    { 
     \\calculates tax recursively calling two other functions difference() and taxStep() 
     tax = tax + difference(taxWage) * taxStep(taxWage); 
     var newSalary = taxWage - difference(taxWage); 
     taxes(tax, newSalary); 
    } 
    else 
    { 
     returnTax = tax + taxWage * taxStep(taxWage); 
     return returnTax; 
    } 
} 

我看不出爲什麼它不會停止遞歸。

+0

什麼是你的問題?而且,這段代碼與你的問題的標題有什麼關係? – jfriend00

+0

謝謝。編輯。 – raam86

+0

你說它遞歸,但沒有代碼在這裏遞歸。 –

回答

7

在這個臂你的函數:

if (taxWage > minWage) { 
    // calculates tax recursively calling two other functions difference() and taxStep() 
    tax = tax + difference(taxWage) * taxStep(taxWage); 
    var newSalary = taxWage - difference(taxWage); 
    taxes(tax, newSalary); 
} 

你是不是從函數返回一個值或設置returnTax。當您不返回任何內容時,返回值爲undefined

也許,你想這樣:

if (taxWage > minWage) { 
    // calculates tax recursively calling two other functions difference() and taxStep() 
    tax = tax + difference(taxWage) * taxStep(taxWage); 
    var newSalary = taxWage - difference(taxWage); 
    return taxes(tax, newSalary); 
} 
3

沒有您的遞歸的錯誤:

taxes(tax, newSalary); 

if條件的計算結果爲true,不返回任何東西。您需要更改到:

return taxes(tax, newSalary); 

你必須在else必要return聲明。