递归功能返回未定义
我的功能可以计算税收。
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;
}
}
我看不出为什么它不会停止递归。
I have a function which calculates taxes.
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;
}
}
I can't see why it doesn't stop the recursion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的功能的此部门中:
您没有从功能或设置
return tax
中返回值。当您不返回任何内容时,返回值为undefined
。也许,您想要这个:
In this arm of your function:
you are not returning a value from the function or setting
returnTax
. When you don't return anything, the return value isundefined
.Perhaps, you want this:
递归中有一个错误:
如果在true中评估中的条件时,您不会返回任何内容。您需要将其更改为:
您在
else> else
中具有必要的返回
语句。There is a bug with your recursion:
You don't return anything when the condition in the
if
evaluates to true. You need to change that to:You have the necessary
return
statement in theelse
.例如
税收(税,新闻);
返回100
;您期望看到
100
,因为您递归地称呼税收(税,新闻)
,但实际上您获得了值(100
),您需要返回此值。返回100
后,您将获得此值。For example
taxes(tax, newSalary);
returns100
;You expect to see
100
because you calledtaxes(tax, newSalary)
recursively but in fact you got the value (100
) and you need to return this value.after
return 100
you will get this value.