【发布时间】:2018-09-08 05:02:44
【问题描述】:
我正在尝试制作一个小型随机测验生成器,第一个数组包含问题并且随机显示(加载页面或刷新页面时),第二个数组包含答案。
现在,当用户输入答案时,如果该答案来自答案数组,则会显示the correct 消息,即使该问题的答案不正确,并且如果答案不是来自答案数组, 显示the not correct 消息。
我需要一个代码来解决这个问题(我可以在 if...else 和 || 和 && 运算符中做到这一点,但是对于超过 5 个条目的代码变得太长且难以维护) 下面是javascript和html代码
//reload whole page
function refreshMe() {
window.location='index.html';
}
const myQs = [
"How many sides has a hexagon", // must always be the first answer from myRs array
"A circle has...degrees?", // must always be the second answer from myRs array
"2^3=...?",
"2+2:2=..?",
"A triangle has....degrees?",
"Square root of 2 is...?" // to be extend up to 500 entries
];
let randomItem = myQs[Math.floor(Math.random()*myQs.length)];
document.getElementById("demo").innerHTML = randomItem;
function userAnswer() {
const check = document.getElementById('answer').value;
const myRs = [
"6",
"360",
"8",
"3",
"180",
"1.41"
];
// the difference between 0 and -1?
if (myRs.indexOf(check) > -1) {
sayMessage = check + " is the correct answer!";
} else {
sayMessage = check + " is not the correct answer....";
}
document.getElementById("userA").innerHTML = sayMessage;
};
对于一个随机问题,现在每个答案都是正确的,如果输入了 myRs 之外的答案,则消息is not correct。我需要一个代码,以便 myQs 数组中的问题与 myRs 数组中自己的答案相匹配,数组中的相同索引,第一个问题有第一个答案,等等。
我可以用 if...else 和 ||和 && 运算符,但是对于超过 5 个条目,代码会变得太长且难以维护。
<p> The question of the moment...</p>
<p id="demo"></p>
<button onclick="refreshMe()">Next one </button><br><br>
<input name="answer" type="text" placeholder="Your answer is....." id="answer">
<br><br>
<button onclick="userAnswer()">Check answer</button>
<p id="userA"></p>
【问题讨论】:
-
使用哈希映射的力量。
标签: javascript arrays string-matching