从函数返回并重新声明变量

时间:2012-08-01 16:11:16

标签: javascript variables return redeclare

为我的介绍编程课程完成一项任务,我创建了一个函数,让一切工作得到了一些人的帮助(感谢一点点顺便说一句),现在我有了一个新问题。我有两个变量,我声明并在启动我的函数之前提示输入一个值,如果它没有通过则导致它提示一个新值。但是现在当我返回它们时,它不会改变代码之外的变量。

// 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由于某种原因显示原始值,而不是返回后在函数中更改的值。

3 个答案:

答案 0 :(得分:2)

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

function treeFunction(answer, counter, numTrees) {

你得到一组新的局部变量,它们碰巧与全局变量同名,因此隐藏它们。

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

function treeFunction() {
   answer = ....

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

答案 1 :(得分:1)

  1. 函数只能返回一个值。所以, return numTrees; return answer;
  2. 第二个陈述不会被执行。

    1. 因为变量是在函数外声明的,所以它们是全局变量。所以,你不需要退货。即,在函数完成执行后它将具有修改的值。

答案 2 :(得分:0)

而不是两次调用return(无论如何都不会有效),您可以返回Array

return [numTrees, answer];

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

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

// ret[0] is "numTrees"
// ret[1] is "answer"