Help us understand the problem. What is going on with this article?

フィボナッチ数を出力する関数を作る

More than 1 year has passed since last update.

再帰関数を書いた事がなかったので、とりあえずフィボナッチ数が適しているだろうと思って書いてみました。
再帰関数という名前に身構えてしまいましたが、意外とシンプルですね。

function F (n) {
  if ( n === 0 || n === 1 ) {
    return 1;
  } else {
    return F(n-1) + F(n-2);
  }
}

ワンライナー

F = (n) => n === 0 || n === 1 ? 1 : F(n-1) + F(n-2);

こんな感じの書き方は冗長な感じがしているので、よりよい書き方を知っている方は是非コメントをよろしくお願いします:pray:

[追記]
コメントでより短いやり方を教えていただきました。
const fib = n => n > 2 ? fib(n - 1) + fib(n - 2) : 1;
基底部のところを後回しにするのがポイントですね。

参考

JavaScript-階乗でみる、初めての再帰関数

siromath
HTML,CSS,JavaScript,Haskellなど
https://blog.siromath.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした