2016-04-04 11 views
-1

私のコードは次のとおりです。誰かが存在しない名前を入力した場合、スイッチにループを張りたいです。私は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."); 
 
}

+0

なぜ7つの同じ「ブレント」ケースが空白になっていますか? –

+0

私のケースすべてが同じアラートを受信するので、アラートが見つかるまでフォールスルーと呼ばれます。私はCodeschool.comを通して学びました –

答えて

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(); 
+0

ありがとう!私はこれを間違いなく試みます! –

0

あなたはあなたのコードが1の内側に配置する場合は、ループの次のステップに行くために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は冗長ですが、あなたはそのアイデアを得ます。

あなたが望むものについてより多くの情報を提供する場合、とにかく、望ましい機能を達成するためのより良い方法があります。

関連する問題