Javascript-将用户输入值与随机生成的值进行比较

时间:2018-10-20 09:47:55

标签: javascript random switch-statement compare

我有一个函数,可以以非重复的方式显示来自数组的随机单词,还有一个文本框,用户可以在该文本框中键入生成的相同单词。

我尝试使用switch语句来验证用户的答案,将其输入与随机生成的单词进行比较,但是它不起作用。

我的问题是,甚至可以比较这些东西吗?如果可以,怎么办?

这是我的代码:

// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];

function randomize() {
  if (remainingWords.length === 0) remainingWords = origWords.slice();
  const {
    length
  } = remainingWords;
  const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
  p.textContent = quote;
}
randomize();

// Validate answer
function submit001() {
  var answers = document.getElementById("input001").value.toLowerCase();
  switch (answers, remainingWords) {
    case "":
      text = "Please write something.";
      break;
    case answers == remainingWords:
      text = "Correct.";
      randomize();
      break;
    default:
      text = "Wrong.";
  }
  document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>

1 个答案:

答案 0 :(得分:1)

if语句可能是解决该问题的更合适方法。试试这个:

// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];

function randomize() {
  if (remainingWords.length === 0) remainingWords = origWords.slice();
  const length = remainingWords;
  const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
  p.textContent = quote;
}
randomize();

// Validate answer
function submit001() {
  var answers = document.getElementById("input001").value.toLowerCase();
  if (answers == "") {
    text = "Please write something.";
  } else if (answers == p.textContent) {
    text = "Correct.";
    randomize();
  } else {
    text = "Wrong.";
  }
  document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>