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();
最佳答案
您的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);
然后可以将该值传递给下一个函数。请记住,您需要对其他功能执行相同的操作。
关于javascript - JS循环迭代但未传递值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26093549/