【发布时间】:2020-09-24 22:03:02
【问题描述】:
我从数组中提取了一个随机问题,从数组中的数组中提取了三个可能的答案。正确答案基于数组中可能答案在数组中的位置,并与 prompt() 中的用户输入进行比较。
ie:[1[correct, x, x], 2[x, correct, x], 3[x, x, correct].
对于第一个随机问题,答案编号与正确答案匹配。在第一个问题之后,程序接受的答案不再与用户输入的正确答案匹配。无论随机问题的顺序如何,都是如此。
例如:
Question 2 (displayed first):
1) x
2) y - correct
3) z
Question 1 (displayed next):
1) a - correct but returns false
2) b - wrong but returns correct
3) c
这是我的代码。输入'quit'结束提示框弹出。
var Question = function(question, answerArray, answer) {
this.question = question;
this.answerArray = answerArray;
this.answer = answer;
};
Question.prototype.questionPrompt = function() {
console.log(this.question);
this.answerArray.forEach(function(answerList, index) {
console.log(index + ') ' + answerList)
});
};
var questionArray = new Array(
q1 = new Question('Question A:', ['A', 'B', 'C'], 'A'),
q2 = new Question('Question B:', ['A', 'B', 'C'], 'B'),
q3 = new Question('Question C:', ['A', 'B', 'C'], 'C')
)
var randomQ = Math.floor(Math.random() * questionArray.length);
questionArray[randomQ].questionPrompt();
Question.prototype.answerPrompt = function() {
var guess = prompt("Enter number of the correct answer.");
var currentQ = randomQ;
var tryQ = guess && Number(guess);
if (currentQ === tryQ) {
console.log('Correct! ' + this.answer);
nextQ();
} else if (guess === "quit") {
console.log("Goodbye.")
} else {
console.log('Try again.' + this.answer);
nextQ();
}
};
questionArray[randomQ].answerPrompt();
var newQ;
function nextQ() {
newQ = Math.floor(Math.random() * questionArray.length);
questionArray[newQ].questionPrompt();
questionArray[newQ].answerPrompt();
};
是什么导致 newQ() 中问题的数组位置与 newQ() 中的答案不同,而 randomQ 的位置保持不变?
【问题讨论】:
-
如果您可以使您的脚本可运行显示我们可以自己完成每一步,这将有很大帮助。在问题编辑器中查找
<>图标以创建 sn-p。 -
不知道
randomQ来自哪里。如果randomQ与页面上问题的顺序有关,而不是在数组中,则它们将不匹配。这是一个很好的例子,说明为什么应该避免基于位置的逻辑,因为它既令人困惑又不必要地脆弱。
标签: javascript