イントロプログラミングクラスの課題に取り組んでいて、関数を作成し、ここにいる何人かの人たちの助けを借りてすべてが機能するようになりました(ありがとう、トンところで)、新しい問題が発生しました。関数を開始する前に宣言して値の入力を求める 2 つの変数があり、それが渡されない場合は新しい値の入力を求めるプロンプトが表示されます。しかし、今それらを返すと、コードの外側の変数は変更されません。
// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";
function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3)
{
if (numTrees < 5 || numTrees > 10)
{
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
alert("You have entered: " + numTrees)
counter + 1;
}
else
{
answer = "yes";
}
}
if (answer == "no") {
alert("You have entered an incorrect number too many times.\nThe Program will now end.");
window.open('', '_self', '');
window.close();
} else if (answer == "yes") {
return numTrees;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees);
document.write("<br/>")
document.write("<br/> <br/>" + "End of Program.");
編集:私は自分がやっていることを変更しました。両方の変数を返す必要がなくなり、numTrees だけを返す必要がなくなりました。ただし、何らかの理由で document.write は元の値を表示し、戻り後も関数で変更された値ではありません。