避免在基本银行应用程序上重置总计

Keep total from resetting on basic banking app

我正在为初学者开发一个基本的银行应用程序 class。

预计:

实际:

有没有办法调整此代码以保持 运行 平衡?

function bankingApp() {
  let currentBalance = 0;
  let userPrompt = prompt(
    "bank menu: w = withdrawal | d = deposit | b = balance |  q = quit"
  );

  switch (userPrompt) {
    case "w":
      function withdrawFunds() {
        let withdrawAmount = parseFloat(prompt("Withdraw amount: "));
        currentBalance = currentBalance - withdrawAmount;
        console.log(
          "Withdraw: " + withdrawAmount + "New balance: " + currentBalance
        );
      }
      withdrawFunds();
      break;

    case "d":
      function depositFunds() {
        let depositAmount = parseFloat(prompt("Deposit amount:"));
        console.log(
          "Deposit: " + depositAmount + "New balance: " + currentBalance
        );
      }
      depositFunds();
      break;

    case "b":
      function checkBalance() {
        let balance = currentBalance;
        console.log(balance);
      }
      checkBalance();
      break;

    case "q":
      function quitProgram() {
        let quit = "Quit the program.";
        console.log(quit);
      }
      quitProgram();
      break;

    default:
      console.log("That menu is not available.");
  }
}

您在事件发生时调用您的函数(单击按钮)。现在你函数中的第一条语句是将余额设置为 0。没有任何东西跟踪它。

只需将语句移出,变量就会保留。

let currentBalance = 0;

function bankingApp() {

  let userPrompt = prompt(
    "bank menu: w = withdrawal | d = deposit | b = balance |  q = quit"
  );

  switch (userPrompt) {
    case "w":
      function withdrawFunds() {
        let withdrawAmount = parseFloat(prompt("Withdraw amount: "));
        currentBalance = currentBalance - withdrawAmount;
        console.log(
          "Withdraw: " + withdrawAmount + "New balance: " + currentBalance
        );
      }
      withdrawFunds();
      break;

    case "d":
      function depositFunds() {
        let depositAmount = parseFloat(prompt("Deposit amount:"));
        console.log(
          "Deposit: " + depositAmount + "New balance: " + currentBalance
        );
      }
      depositFunds();
      break;

    case "b":
      function checkBalance() {
        let balance = currentBalance;
        console.log(balance);
      }
      checkBalance();
      break;

    case "q":
      function quitProgram() {
        let quit = "Quit the program.";
        console.log(quit);
      }
      quitProgram();
      break;

    default:
      console.log("That menu is not available.");
  }
}