简体   繁体   English

如何使我的用户响应不区分大小写?

[英]How do I make my user responses NOT case sensitive?

I've hit a brick wall. 我撞到了砖墙。 I'm trying to write my code so that the when the user types a response into the prompt box, their answers are not required to be case sensitive in order for it to be correct. 我正在尝试编写代码,以便当用户在提示框中键入响应时,要求他们的答案区分大小写才能正确。 Any suggestions? 有什么建议么?

Here is my code: 这是我的代码:

var questions = [
  ["What solar system do we live in?", "Milky Way"],
  ["How many ounces are in a cup?", "16"],
  ["What type of cellphone is currently the most popular throughout the world?", "iPhone"],
  ["What's Chicago's tallest building?", "Willis Tower"],
  ["What is the name of the Chicago White Sox' new stadium?", "Guaranteed Rate"]
];

var correctAnswers = 0;
var question;
var answer;
var response;
var html;
var correct = [];
var wrong = [];

function print(message) {
  var outputDiv = document.getElementById("output");
  outputDiv.innerHTML = message;
}

function buildList(arr) {
  var listHTML = "<ol>";
    for(var i=0;i<arr.length;i++) {
      listHTML += "<li>" + arr[i] + "</li>";
    }
  listHTML += "</ol>";
  return listHTML;
}

for(var i=0;i<questions.length;i++) {
  question = questions[i][0];
  answer = questions[i][1];
  response = prompt(question);
  if(response === answer) {
    correctAnswers += 1;
    correct.push(question);
  } else {
    wrong.push(question); 
  }
}

html = "You got " + correctAnswers + " question(s) right.";
html += "<h2>You got these questions correct:</h2>";
html += buildList(correct);
html += "<h2>You got these questions wrong:</h2>";
html += buildList(wrong);
print(html);

Just compare them with all lowerCase or all upperCase : 只需将它们与所有lowerCase或所有upperCase进行比较:

if(response.toLowerCase() === answer.toLowerCase()) {

That way you allow the user to write it any way he wants but still validate correctly 这样,您就可以让用户以他想要的任何方式编写它,但仍然可以正确验证

You could call toLowerCase() or toUpperCase() on both the response and answer variables 您可以在响应变量和答案变量上调用toLowerCase()toUpperCase()

if(response.toUpperCase() === answer.toUpperCase()) {
    correctAnswers += 1;
    correct.push(question);
  } else {
    wrong.push(question); 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM