不区分大小写的提示即使使用 toLowerCase也不起作用

A Case-Insensitive Prompt Not Working Even With The Use of toLowerCase

本文关键字:toLowerCase 不起作用 大小写 提示 不区      更新时间:2023-09-26

我正在学习JavaScript,并决定做一段基本的Switch代码。我正在尝试使用 .toLowerCase 使我的提示输入不区分大小写。但是,这是行不通的:

document.getElementById("button").onclick=function(){
   var question = prompt("How do you do");
    switch(question) {
       case "Great".toLowerCase: 
          alert("Excellent!");
          break;
       case "Good".toLowerCase: 
          var question_2 = prompt("Could it be better?");
         if(question_2 == "yes") {
           alert("Well lets hope tomorrow is better!")     
         }
         else {
           alert("Phew! You got me for a moment!")   
         }
         break;
       case "Bad".toLowerCase:
          var q_3=prompt("What happened!");
         if(q_3) {
           alert("I hope tomorrow is better!");
         }
         else {
          alert("I didn't quite get that..");
         }
         break;
       default: alert("I didn't understand...");
     }
  }

每次我插入文本时,无论正确与否,我总是会得到"我不明白",我认为任何输入都是错误的。例如,如果我在"问题"提示中插入"很棒"或"很棒"甚至"很棒",我总是会得到"我不明白"作为警报。有什么帮助吗?

这里有几个问题:

  1. 您需要在问题上调用 toLowerCase(),而不是在正在比较的值问题上调用。 这样,如果用户键入"GrEaT",它将转换为"great",然后再检查您的字符串文字。
  2. toLowerLetter是一种方法。 所以它必须在末尾用 () 调用。 如果你在变量'x'上调用该方法,你的代码将是x.toLowerCase()。
  3. 案例条件也需要小写,以便它们与小写问题匹配,例如"很棒"需要是"很棒"。
尝试在

prompt的返回结果中使用toLowerCase()方法。

document.getElementById("button").onclick=function() {
  var question = prompt("How do you do") || "";
  switch(question.toLowerCase()) {
     case "great": 
        alert("Excellent!");
        break;
     case "good": 
        var question_2 = prompt("Could it be better?") || "";
       if(question_2.toLowerCase() == "yes") {
         alert("Well lets hope tomorrow is better!")     
       }
       else {
         alert("Phew! You got me for a moment!")   
       }
       break;
     case "bad":
        var q_3 = prompt("What happened!") || "";
       if(q_3) {
         alert("I hope tomorrow is better!");
       }
       else {
        alert("I didn't quite get that..");
       }
       break;
     default: alert("I didn't understand...");
   }
};

呵。

相关文章: