JavaScriptの再帰基本
3718 ワード
再帰とは何か
The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion). https://developer.mozilla.org/en-US/docs/Glossary/Recursion
2例
ベースケース-私たちの答えを返す必要がありますか?いつ停止する必要がありますか?
再帰的なケース-我々はどのように我々の議論を操作しますか、あるいは、我々はもう一つの再起動のために引数を調節することができますか?
例- count ()
"1羊"を出力する関数count ()を作成する入力番号「X羊」までずっと
テクニックを使って解決しましょう
p - integer ( x )羊の数、count = 0のデフォルト引数で、現在の羊番号
R - 1からx
下記参照
// countSheep(3)
// 1 sheep...
// 2 sheep...
// 3 sheep...
p -
再帰的な場合- 1を加えることによってカウントを変更して、現在のカウントのコンソールを返します
function countSheep(x, count=0) {
// BASE CASE
// return if count equals x, which means every sheep is counted
// RECURSIVE CASE
// modify argument by adding 1 to count
// log current count & reinvoke w/ modification
}
さて、コードロジックを実装します.function countSheep(x, count=0) {
// BASE CASE
// return if count equals x, which means every sheep is counted
if (count === x ) return;
// RECURSIVE CASE
// modify argument by adding 1 to count
count++
// log current count & reinvoke w/ modification
return console.log(x + ' sheep...') + countSheep(x, count)
}
結論
再帰的な解決策を見つけるとき、常に基本的なケースと再帰的なケースが何であるかについて、心に留めておいてください.それは良い方法を開始することです!
覚えて.ハッピーコーディング、友達!=
Reference
この問題について(JavaScriptの再帰基本), 我々は、より多くの情報をここで見つけました https://dev.to/phariale/recursion-basics-in-javascript-4f5iテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol