おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第108弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Basic JavaScriptの中の、
Use Recursion to Create a Countdown
です。
さっそく見ていきましょう。
まずは本文から。
In a previous challenge, you learned how to use recursion to replace a for loop. Now, let’s look at a more complex function that returns an array of consecutive integers starting with
1
through the number passed to the function.As mentioned in the previous challenge, there will be a base case. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a recursive call which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached.
For example, say you want to write a recursive function that returns an array containing the numbers
1
throughn
. This function will need to accept an argument,n
, representing the final number. Then it will need to call itself with progressively smaller values ofn
until it reaches1
. You could write the function as follows:function countup(n) {if (n < 1) {return [];} else {const countArray = countup(n – 1);countArray.push(n);return countArray;}}console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]At first, this seems counterintuitive since the value of n
decreases, but the values in the final array are increasing. This happens because the push happens last, after the recursive call has returned. At the point wheren
is pushed into the array,count(n - 1)
has already been evaluated and returned[1, 2, ..., n - 1]
.We have defined a function called countdown
with one parameter (n
). The function should use recursion to return an array containing the integersn
through1
based on then
parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function withn = 5
should return the array[5, 4, 3, 2, 1]
. Your function must use recursion by calling itself and must not use loops of any kind.
解説していきます。
今回は再帰関数の複雑な処理についてです。
1からnの数値を含む配列を返す再帰関数について考えてみましょう。
この関数は、最終的な数値を表す引数nをとります。そして、1に達するまでnの値を徐々に小さくして自分自身を呼び出し、その都度配列を吐き出せば行けそうですね。
次のように書くことができます。