如何实现循环,以使程序不会崩溃?

时间:2019-02-09 02:08:12

标签: javascript string webpage

我是一个初学者,我遇到了这个Javascript问题。我需要提示用户输入R / r或F / f。但是,我想实现一个循环,以便万一它们输入其他内容,我的程序不会崩溃。我将如何去做?

function CalculatePayroll()
{
employeeNumber=prompt("Please enter the employee number");
employeeName=prompt("Please enter the employee's name");
employeeDepartment=prompt("Please enter the employee's department");
employeesHours=prompt("Please enter the number of hours the employee 
worked");
employeeTypeCode=prompt("Please enter the employee's type code: F/f or 
R/r");

  if(employeeTypeCode=="R"||employeeTypeCode=="r")
  {
    RegularWorkerPayroll();
    CalculateTotalPay();
    DisplayPaySlip();

  }

  else if(employeeTypeCode=="F"||employeeTypeCode=="f")
  {
    FacultyPayroll();
    CalculateTotalPay();
    DisplayPaySlip();
  }
}

我想实现一个循环,这样,如果它们输入“ b”之类的东西,我可以不断地提示他们,直到他们输入正确的字符为止。我尝试了几次,但最终遇到了无限循环大声笑。

3 个答案:

答案 0 :(得分:1)

您可以将while循环用于测试数组和includes。然后使用switchtoLowerCase调用函数:

employeeTypeCode=prompt("Please enter the employee's type code: F/f or R/r");

while (!["F", "f", "R", "r"].includes(employeeTypeCode)) {
    employeeTypeCode=prompt("Please enter the employee's type code: F/f or R/r");
}

switch (employeeTypeCode.toLowerCase()) {
    case "f":
        FacultyPayroll();
        break;
    case "r":
        RegularWorkerPayroll();
        break;
}

CalculateTotalPay();
DisplayPaySlip();

答案 1 :(得分:0)

使用如下所示的while循环:

var employeeTypeCode;

while (employeeTypeCode != "r" && employeeTypeCode != "f") {
  employeeTypeCode = prompt("Please enter the employee's type code: F/f or R/r").toLowerCase();
}

答案 2 :(得分:0)

您可以使用do-while循环来获取用户输入,并在输入无效选项时继续请求输入。

您可以在输入中使用.toLowerCase(),因此只需要检查字母的小写版本即可。然后,您还可以使用对象将字母映射到特定的函数,该函数为此employeeTypeCode调用关联的函数,

function calculatePayroll() {
  var options = {
    'r': RegularWorkerPayroll,
    'f': FacultyPayroll
  }

  employeeNumber = prompt("Please enter the employee number");
  employeeName = prompt("Please enter the employee's name");
  employeeDepartment = prompt("Please enter the employee's department");
  employeesHours = prompt("Please enter the number of hours the employee worked ");

  do {
    employeeTypeCode = prompt("Please enter the employee's type code: F/f or R / r ").toLowerCase();
  } while(employeeTypeCode !== "r" && employeeTypeCode !== "f");

  options[employeeTypeCode]();
  CalculateTotalPay();
  DisplayPaySlip();
}

此外,通常好的做法是,如果函数名是构造函数而不是像这样的常规函数​​,则仅对函数名使用大写字母。