19

我有一个计算税金的函数。

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

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

4

3 回答 3

41

在您的职能部门中:

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); 
}
于 2012-10-05T00:49:05.610 回答
14

您的递归存在错误:

taxes(tax, newSalary);

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

return taxes(tax, newSalary);

returnelse.

于 2012-10-05T00:48:23.627 回答
0

例如taxes(tax, newSalary);返回100

taxes(tax, newSalary); // undefined

您希望看到100,因为您taxes(tax, newSalary)递归调用但实际上您获得了值 ( 100) 并且您需要返回该值。

return taxes(tax, newSalary); // 100
// simply it's the same as
// return 100
// because taxes(tax, newSalary) returned 100

return 100你得到这个值之后。

于 2022-02-06T18:21:43.653 回答