我有一个计算税金的函数。
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);
}
你的递归有一个错误:
taxes(tax, newSalary);
当
if
中的条件评估为 true 时,您不会返回任何内容。您需要将其更改为:
return taxes(tax, newSalary);
您在
return
中有必要的 else
声明。
例如
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
之后你将得到这个值。