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

Gre*_*gle 2 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
Run Code Online (Sandbox Code Playgroud)

这很好用.1年后5万美元的10,000美元是10,500美元; 10年后,16,288美元.

现在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这会回来undefined,但我无法弄清楚原因.它invest使用正确的参数调用正确的次数,逻辑是相同的.该compound功能的工作原理,我测试了一下分开.那么......可能出错了什么?

小智 5

如果逐步代码"脱落"函数的末尾,Ruby函数会自动返回最后一个表达式的值.JavaScript(和大多数其他编程语言)这样做,所以你需要返回值else显式子句中:

function invest(amount, years, rate) {
    if (years === 0) {
        return amount;
    } else {
       return invest(compound(amount, 5), years - 1, rate);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用条件运算符:

function invest(amount, years, rate) {
    return years === 0 ? amount : invest(compound(amount, 5), years - 1, rate);
}
Run Code Online (Sandbox Code Playgroud)