>我有一个函数,以非重复的方式显示数组中的随机单词,以及一个文本框,用户应该在其中键入相同的生成单词。
我尝试使用 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>