我有一个计算税收的功能。
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;
}
}
我不明白为什么它不能阻止递归。
答案 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
声明。