0

在为我的 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 显示的是原始值,而不是返回后在函数中更改为的值。

4

3 回答 3

2

answer, counter, numTrees是全局的,但是当您将它们作为参数传递给函数时;

function treeFunction(answer, counter, numTrees) {

你会得到一组新的局部变量,它们恰好与全局变量同名,因此隐藏了它们。

要使用全局变量,请不要传递它们

function treeFunction() {
   answer = ....

(您还想counter += 1实际增加变量)

于 2012-08-01T16:19:23.113 回答
1
  1. 一个函数只能返回一个值。所以, return numTrees; return answer;

第二条语句不会被执行。

  1. 由于变量是在函数外部声明的,因此它们是全局的。所以,你不需要退货。即,函数完成执行后,它将具有修改的值。
于 2012-08-01T16:16:43.370 回答
0

而不是调用return两次(无论如何都不起作用),您可以返回一个Array.

return [numTrees, answer];

所以现在我们可以通过分配返回值来捕获它并访问它:

var ret = treeFunction(answer, counter, numTrees);

// ret[0] is "numTrees"
// ret[1] is "answer"
于 2012-08-01T16:16:14.647 回答