在Ruby和JS中编写相同的函数,Ruby可以工作,但JS是未定义的

Wrote the same function in Ruby and JS, Ruby works but JS is undefined

本文关键字:JS Ruby 未定义 工作 函数      更新时间:2023-09-26

我想尝试用递归来计算复利,而不是循环。

在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%利率计算为10,500美元;10年后,16288美元。

现在JavaScript (ES6)的逻辑是一样的。

function compound(balance, percentage) {
    return balance + percentage / 100 * balance;
}
function invest(amount, years, rate) {
    if (years === 0) {
        return amount;
    } else {
        invest(compound(amount, 5), years - 1, rate);
    }
}

返回undefined,但我不知道为什么。它调用invest的次数是正确的,参数是正确的,逻辑是一样的。compound功能工作,我单独测试了。所以…会出什么问题呢?

如果分步代码在函数结束时"脱落",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);
}