【问题标题】:Trying to get a switch to loop over when the default occurs尝试在默认情况发生时让开关循环
【发布时间】:2016-04-04 20:43:09
【问题描述】:

这是我的代码:如果有人输入不存在的名称,我希望我的开关循环。我是 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.");
}

【问题讨论】:

  • 为什么你有七个相同的brent 空白案例?
  • 它被称为失败,因为我的所有案例都会收到相同的警报,我只是让它失败,直到它找到警报。我是通过 Codeschool.com 了解的

标签: javascript switch-statement prompt


【解决方案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();

【讨论】:

  • 谢谢!我一定会试试这个!
【解决方案2】:

如果您将代码放入其中,您可以使用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 是多余的,但您明白了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多