在为我的 Intro Programming 课程做作业时,我创建了一个函数,并在这里得到了一些人的帮助(非常感谢),现在我遇到了一个新问题。我有两个变量,我声明并在启动我的函数之前提示输入一个值,如果它没有通过,它会提示它输入一个新值。但是现在当我返回它们时,它不会更改代码之外的变量。
// 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 显示的是原始值,而不是返回后在函数中更改为的值。