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

标签 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>

最佳答案

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>

关于Javascript - 将用户输入值与随机生成的值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904370/

相关文章:

javascript - 向文本溢出 : ellipsis 的元素添加标题属性

javascript - 带有自定义值的复选框 ng-required 在最新的 AngularJS 中不起作用

Javascript 命名空间和条件包含

c - C的rand()有哪些常用算法?

string - 在Groovy中打开字符串值会产生意外的结果

node.js - JS/node.js : Large switch-case blocks vs. 函数集合

javascript - 函数调用 [javascript]

python - 在 __init__ 中使用 While 循环来满足 Python 中的特定条件

c++ - 如何在 C++ 中随机移动一个球?

java - (Java) 在 Switch Case 中使用空行退出 While 循环