小编典典

递归函数返回未定义

javascript

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

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

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


阅读 353

收藏
2020-05-01

共1个答案

小编典典

在您的职能部门中:

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); 
}
2020-05-01