javascript - 有没有更好的方法来解决 JavaScript 中的递归斐波那契
问题描述
我想返回给定数字的斐波那契数列;我想递归地这样做。
这是我的工作解决方案:
function fibonacci(number, previous = 0, current = 0, index = 1) {
if (index === number) {
return [current + previous]
}
return [(index < 3) ? 1 : current + previous]
.concat(fibonacci(number, current, (index < 3) ? 1 : current + previous, index + 1))
}
console.log(JSON.stringify(fibonacci(7)))
有没有办法在只使用一个函数的同时摆脱条件(三元)运算符?
解决方案
这就是我会做的。
const fibs = (a, b, n) => n > 0 ? [a, ...fibs(b, a + b, n - 1)] : [];
const fibonacci = n => fibs(1, 1, n);
console.log(JSON.stringify(fibonacci(7)));
您也可以使用默认参数。
const fibonacci = (n, a = 1, b = 1) =>
n > 0 ? [a, ...fibonacci(n - 1, b, a + b)] : [];
console.log(JSON.stringify(fibonacci(7)));
就个人而言,我不喜欢使用默认参数。
推荐阅读
- xslt-2.0 - 在 XSLT 中对数据进行分组后计算行数
- f# - 是否可以编写一个将文件(SFTP)传输到远程服务器并在该服务器上运行一些 docker 命令的 FAKE 构建脚本?
- amazon-dynamodb - Flink 运动连接器 - KCL
- mysql - SQL查询以分组方式查找最大值的行
- sql - 什么类型的 sql db 可以在一列中存储声音或数组数据?
- caching - Hapi js客户端缓存
- javascript - VS 代码得到假错误?
- php - 在 codeigniter 控制器中从 CURL 读取返回的 JSON
- strapi - 内容管理器上的新帖子未触发 Strapi 服务“创建”
- https - 使用 https://localhost url 时 lighthouse-ci 一直失败