Javascript 在Ruby和JS中编写了相同的函数,Ruby可以工作,但JS没有定义
我想尝试递归来计算复利,而不是循环 在Ruby中:Javascript 在Ruby和JS中编写了相同的函数,Ruby可以工作,但JS没有定义,javascript,Javascript,我想尝试递归来计算复利,而不是循环 在Ruby中: def compound balance, percentage balance + percentage / 100 * balance end def invest amount, years, rate return amount if years == 0 invest compound(amount, rate), years - 1, rate end 这个很好用$1年后按5%计算的10000美元为10500美元;1
def compound balance, percentage
balance + percentage / 100 * balance
end
def invest amount, years, rate
return amount if years == 0
invest compound(amount, rate), years - 1, rate
end
这个很好用$1年后按5%计算的10000美元为10500美元;10年后,16288美元
现在,JavaScript(ES6)中的逻辑相同
这将返回未定义的
,
,但我不知道为什么。它调用invest
的次数正确,参数正确,逻辑相同。复合
函数可以工作,我单独测试了它。所以有什么问题吗?如果分步代码从函数末尾“脱落”,Ruby函数会自动返回最后一个表达式的值。JavaScript(和大多数其他编程语言)不这样做,因此需要在else
子句中显式返回值:
function invest(amount, years, rate) {
if (years === 0) {
return amount;
} else {
return invest(compound(amount, 5), years - 1, rate);
}
}
或使用条件运算符:
function invest(amount, years, rate) {
return years === 0 ? amount : invest(compound(amount, 5), years - 1, rate);
}
啊,这就解决了。谢谢你。我确实知道JS缺少隐式返回,但我假设最终的
返回量将从整个递归调用系列返回。我猜它只是返回到调用它的堆栈帧?
function invest(amount, years, rate) {
return years === 0 ? amount : invest(compound(amount, 5), years - 1, rate);
}