尝试在默认情况下切换到循环

时间:2016-04-04 20:43:09

标签: javascript switch-statement prompt

这是我的代码:如果有人输入不存在的名称,我希望我的开关循环。我是JavaScript的新手,我正在学习JavaScript工作,这是我刚刚练习的东西。它的功能是明智的,我只是试图找到一种方法,如果它通过默认情况下使其循环。谢谢!为了不使用我的同事姓名,我已将所有案件改为我的名字。

String.prototype.capitalizeFirstLetter = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

var name = prompt("Please enter the name of the recipient to recieve a burn notice").toLowerCase();


switch (name) {
  case 'brent':
  case 'brent':
  case 'brent':
  case 'brent':
  case 'brent':
  case 'brent':
  case 'brent':
  case 'brent':
    alert(name.capitalizeFirstLetter() + " has revieved a burn notice, ice is located downstairs in the freezer.");
    break;
  default:
    alert("Didn't find " + name.capitalizeFirstLetter() + " please try again.");
}

2 个答案:

答案 0 :(得分:1)

将代码放入函数中,如果达到默认情况,请再次调用它。

function askForName() {
  var name = prompt("Please enter the name of the recipient to recieve a burn notice").toLowerCase();

  switch (name) {
    case 'brent':
      alert(name.capitalizeFirstLetter() + " has revieved a burn notice, ice is located downstairs in the freezer.");
      break;
    default:
      alert("Didn't find " + name.capitalizeFirstLetter() + " please try again.");
      askForName();
  }
}

// initial call to make sure the function runs
askForName();

答案 1 :(得分:0)

如果您将代码放在一个循环中,则可以使用continue转到循环的下一步。

for(;;) {
    var name = prompt("Please enter the name of the recipient to recieve a burn notice").toLowerCase();
    switch (name) {
        case 'brent':
            alert(name.capitalizeFirstLetter() + " has revieved a burn notice, ice is located downstairs in the freezer.");
            break;
        default:
            alert("Didn't find " + name.capitalizeFirstLetter() + " please try again.");
            continue;
    }
}

在示例中,continue是多余的,但您明白了。

无论如何,如果您提供有关您想要的更多信息,那么有更好的方法来实现所需的功能。