税务计算中未定义的递归
在此递归税务计算函数中:
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; } }
递归无法终止。具体来说,问题在于调用递归调用的函数臂:
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); }
此更改可确保函数返回递归调用的结果,正确地将值沿着递归链传播。
以上是为什么这个递归税务计算函数会导致未定义的递归?的详细内容。更多信息请关注PHP中文网其他相关文章!