JS循环迭代,但未传递值

时间:2014-09-29 06:14:44

标签: javascript

getBottles()中的循环迭代,但不会将totalBottles的值传递给main()。 我是JS的新手,可以使用一些更好的细节帮助。当运行脚本时,为totalBottles返回0。请帮忙。

//main function calls other functions
function main(){
   var totalBottles = 0;
   var counter = 1;
   var todayBottles = 0;
   var totalPayout = 0;
   var keepGoing = "y";

   while(keepGoing == "y"){
      getBottles(totalBottles, todayBottles, counter);
      calcPayout(totalPayout, totalBottles);
      printInfo(totalBottles, totalPayout);
      inputStr = prompt("Do you want to run the program again? (Enter y for yes)");
      keepGoing = inputStr;
   }
}
//getBottles function gets loops to get # bottles each day for a week
function getBottles(totalBottles, todayBottles, counter){
   while(counter <= 7){
      inputStr = prompt("Enter number of bottles returned for the day:");
      todayBottles = parseFloat(inputStr);
      totalBottles = totalBottles + todayBottles;
      counter = counter + 1;
   }  return totalBottles;
}

//calcPayout function calculates payout for all bottles returned in a week
function calcPayout(totalPayout, totalBottles){
   totalPayout = 0;
   totalPayout = totalBottles * .10;
   return totalPayout;
}

//printInfo function displays totsl bottles and total payout for week
function printInfo(totalBottles, totalPayout){
   alert("Total bottles returned this week: " + totalBottles);
   alert("Total payout this week: $" + totalPayout.toFixed(2));
}  

main(); 

1 个答案:

答案 0 :(得分:1)

你的getBottles函数没有修改你在main中声明的totalBottles变量,因为它被你在getBottles中声明为参数的局部变量所遮蔽:

function getBottles(totalBottles, todayBottles, counter) {...} // totalBottles here is a local variable to getBottles as are the other parameters

此函数声明中的totalBottles成为此函数的局部变量,这意味着对totalBottles的任何修改仅由此函数的主体所知。您从函数返回此值,但由于您从未将该返回值分配给任何内容,因此该值基本上被丢弃。您的其他函数也是如此,例如calcPayout。你有几个选择。您可以更改函数签名,这样就不会再将使用声明为函数参数的局部变量隐藏在main中声明的变量:

function getBottles() {...}

通过这样做,你不会将变量传递给函数,而只是在main()的范围内使用它们:

getBottles();    

有了这个,getBottles在totalBottles,todayBottles和counter变量上形成一个闭包,这些变量将被getBottles使用和修改。您的其他选项是分配返回值:

var bottles = getBottles(totalBottles, todayBottles, counter);

然后可以将该值传递给下一个函数。请记住,您需要对其他功能执行相同的操作。