raa*_*m86 6 javascript recursion return
我有一个计算税收的功能.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它不会停止递归.
jfr*_*d00 15
在你的功能的这一臂:
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);
}
Run Code Online (Sandbox Code Playgroud)
您没有从函数或设置返回值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);
}
Run Code Online (Sandbox Code Playgroud)
你的递归有一个错误:
taxes(tax, newSalary);
Run Code Online (Sandbox Code Playgroud)
当计算中的条件if为true 时,您不返回任何内容.您需要将其更改为:
return taxes(tax, newSalary);
Run Code Online (Sandbox Code Playgroud)
你有必要的return陈述else.