递归函数返回undefined

raa*_*m86 6 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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它不会停止递归.

jfr*_*d00 15

在你的功能的这一臂:

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); 
}
Run Code Online (Sandbox Code Playgroud)

您没有从函数或设置返回值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); 
}
Run Code Online (Sandbox Code Playgroud)


dsh*_*dsh 8

你的递归有一个错误:

taxes(tax, newSalary);
Run Code Online (Sandbox Code Playgroud)

当计算中的条件if为true 时,您不返回任何内容.您需要将其更改为:

return taxes(tax, newSalary);
Run Code Online (Sandbox Code Playgroud)

你有必要的return陈述else.

  • 如果您希望函数返回一个值,那么您必须返回一个值。在 javascript 中,没有“return”的函数将返回“undefined”。递归本身不需要返回(例如:打印出树中的节点),但是如果您希望函数返回某些内容,那么它需要“return”。您可以通过在调试器中单步执行该函数来探索这一点。 (4认同)
  • 这很有帮助,但我有兴趣知道为什么“return”对于递归的正确运行是必要的。 (2认同)