簡體   English   中英

如何使我的用戶響應不區分大小寫?

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

我撞到了磚牆。 我正在嘗試編寫代碼,以便當用戶在提示框中鍵入響應時,要求他們的答案區分大小寫才能正確。 有什么建議么?

這是我的代碼:

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);

只需將它們與所有lowerCase或所有upperCase進行比較:

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

這樣,您就可以讓用戶以他想要的任何方式編寫它,但仍然可以正確驗證

您可以在響應變量和答案變量上調用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