递归函数返回undefined

时间:2012-10-05 00:37:41

标签: javascript recursion return

我有一个计算税收的功能。

function taxes(tax, taxWage) 
{
    var minWage = firstTier; //defined as a global variable
    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;
    }
} 

我不明白为什么它不能阻止递归。

2 个答案:

答案 0 :(得分:14)

在你的职能部门:

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); 
}

答案 1 :(得分:8)

您的递归存在错误:

taxes(tax, newSalary);

if中的条件评估为真时,您不会返回任何内容。您需要将其更改为:

return taxes(tax, newSalary);

return中有必要的else声明。