javascript - 我的 if else 语句中的变量数字没有更新

标签 javascript if-statement while-loop

我正在尝试运行这个简单的银行“应用程序”,但我无法正确更新值。我尝试通过按“d”作为第一个输入提示 userDesposit,然后按“b”提示 userBalance,但无论我输入什么数字,该值始终会被警告为 0。另外,在我第一次运行时,在提示一些选择后我无法让它退出 - 但如果我按“q”作为我的第一选择,我可以让它立即退出。有人可以帮我解决这些问题吗?谢谢!

function userBank() { 
  let userBalance = 0;
  let continueBanking = true; 
  let userInput = prompt ("Enter 'q' to quit immediately, Enter 'w' to withdraw money, Enter 'd' to deposit money, Enter 'b' to view your balance.");
  
  while (continueBanking == true) {
    if (userInput == "w") {
      let userWithdraw = prompt ("How much would you like to withdraw?");
      userBalance = userWithdraw;
      userBank();
    } else if (userInput == "d") {
  	  let userDeposit = prompt("How much would you like to deposit?");
  	  userBalance = userDeposit;
      userBank();
    } else if (userInput == "b") {
      alert("Here is your current balance: " + userBalance);
      userBank();
    } else if (userInput == "q") {
      alert("Banking app is now closing.");
      continueBanking == false;
      return;
    }
    else {
      alert("Invalid user input. Try again.");
      return;
    }
  }
}

userBank();

最佳答案

您不应该递归调用该函数。由于 while 循环,它已经重复了。每个递归级别都有自己的 userBalance 变量副本,该副本初始化为 0

递归也使得退出应用程序变得困难。您必须输入 q 次数与它的递归次数相同。

您只需将操作提示移动到循环内,而不用再次调用该函数。

您也不需要添加和减去用户存款和取款的金额,您只需设置余额即可。

function userBank() {
  let userBalance = 0;

  while (true) {
    let userInput = prompt("Enter 'q' to quit immediately, Enter 'w' to withdraw money, Enter 'd' to deposit money, Enter 'b' to view your balance.");
    if (userInput == "w") {
      let userWithdraw = prompt("How much would you like to withdraw?");
      userBalance -= parseFloat(userWithdraw);
    } else if (userInput == "d") {
      let userDeposit = prompt("How much would you like to deposit?");
      userBalance += parseFloat(userDeposit);
    } else if (userInput == "b") {
      alert("Here is your current balance: " + userBalance);
    } else if (userInput == "q") {
      alert("Banking app is now closing.");
      break;
    } else {
      alert("Invalid user input. Try again.");
    }
  }
}

userBank();

关于javascript - 我的 if else 语句中的变量数字没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60330541/

相关文章:

javascript - 递归,递归应用示例

If语句的C#重构

c++ - 在无限循环 C++ 中定义一次变量

javascript - MVC 6 使用 ajax 将模型从 View 传递到 Controller 再到局部 View

javascript - 为什么 ctx.drawImage 只是将视频元素的一部分绘制到 Canvas 上?

javascript - 退出 Javascript 中的 if block

PHP:不使用 else 使用简短的 if 语句?

java - 如何将文件中的数字列表放入数组并返回数组

java - java中无效输入后重新提示用户(try and catch)

javascript - Node JavaScript 文件和全局命名空间