在Ruby和JS中编写相同的函数,Ruby可以工作,但JS是未定义的
Wrote the same function in Ruby and JS, Ruby works but JS is undefined
我想尝试用递归来计算复利,而不是循环。
在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);
}
相关文章:
- Ruby/JS如何在提交按钮后重新加载页面
- 使用Ruby数组使用JS在视图中进行迭代和显示
- 在Sinatra(ruby)中实现JS模糊搜索
- 如何使用 Ruby 在 Javascript (js.erb) 中设置 url
- 如何将.js从视图移动到单独的资产 - Ruby On Rails
- 如何在Ruby on Rails中集成Arbor.js
- 如何判断字符串中字母的索引?(在Python、JS、Ruby、PHP等中)
- 如何将ruby on rails数据馈送到d3.js中
- 如何在ruby on rails中保存和发布Webgl中的JS代码结果
- 有没有一种方法可以让Ruby在提供.js文件之前对其进行编辑
- ruby Mustache.render没有像JS Mustache.render这样的部分的第三个参数
- 在application.js中使用嵌入式ruby
- 椭圆曲线加密与JS中的SJCL和Ruby中的OpenSSL
- 如何使从数据库获取的 Ruby 代码在 JS 中工作
- Ruby on Rails 在 js.erb 中渲染 json
- Angular.js integration with Ruby On Rails Forms
- 如何将计算值绑定到 Angular 中的 ng-model 字段.js以便我可以使用 Ruby on Rails 将完整
- 避免HTML请求,只在rails上调用js-ruby
- JS / Ruby AES 256 symmetry
- 如何使用Asana' JS/Ruby库连接Asana' API