Rubber duck debuggingは、論理エラーを見つけるのに適した方法です。コメントの内容は、行ごとにコードをステップ実行しながら、ゴム鴨に大声で言うことです。
function guessAge() {
/*
I'm asking the user for input with a default value of 100
I'm then parsing a string to an integer that is base 10
I store the result in userInput
*/
var userInput = parseInt(prompt("Guess my age!", 100), 10);
/*I check if the user input is 25 */
if (userInput == 25) {
/* The user input is 25 so I alert that they are correct */
alert("Correct!");
} else {
/* otherwise I alert that they are incorrect */
alert("Incorrect");
}
/*I return what guessAge returns. Right now there is no other
return statements out of the function so I will always call
this line */
return guessAge();
}
最初のパススルーの後、もう一度このステップを実行しますが、今度はやりたいことを言う。
function guessAge() {
/*
I want the user input to see if they can guess my age
*/
var userInput = parseInt(prompt("Guess my age!", 100), 10);
/*I check if the user input is 25 */
if (userInput == 25) {
/* The user input is 25 so I alert that they are correct */
alert("Correct!");
/* I want to leave the function guessAge after the user guesses
correctly. */
} else {
/* otherwise I alert that they are incorrect */
alert("Incorrect");
/* I want to call guessAge again since the user guessed wrong */
}
/* this statement is out of my control flow block so it will always
be reached, even if the user entered the correct age. I want to
leave the function when the user enters the correct answer but
this line will allways call guessAge */
return guessAge();
}
そこからいくつかの解決策を試すことができます。問題を解決するには複数の方法があることを忘れないでください。
function guessAge() {
var userInput = parseInt(prompt("Guess my age!", 100), 10);
if (userInput == 25) {
alert("Correct!");
/* I want to leave the function guessAge after the user guesses
correctly. if I do nothing after my else we will leave the
function without having to do anything */
} else {
alert("Incorrect");
/* I want to call guessAge again since the user guessed wrong */
guessAge();
}
}
関数から何も返す必要はありません。また、関数を呼び出すときに必ず返される必要はありません。関数呼び出し元に値を返すときは、returnを使用します。
ヒント:答えが正しいときは、 'guessAge()'をもう一度呼び出せますか?いいえ、しかし答えは何にも関係なく、あなたは再帰的にそれを呼び出します。 –