var quiz = [
["What is Superman's real name?", "Clarke Kent"],
["What is Wonderwoman's real name?", "Dianna Prince"],
["What is Batman's real name?", "Bruce Wayne"]
];
var score = 0 // initialize score
play(quiz);
function play(quiz) {
for (var i = 0, question, answer, max = quiz.length; i < max; i++) {
question = quiz[i][0];
answer = ask(question);
check(answer);
} // end of main game loop gameOver();
}
}
function ask(question) {
return prompt(question);
}
这是我从控制台日志中收到错误消息的位置
Uncaught ReferenceError: i is not defined
at check (VM13 novice.js:26)
at play (VM13 novice.js:16)
at VM13 novice.js:5
function check(answer) {
if (answer === quiz[i][1]) {
alert("Correct!");
score++;
} else {
alert("Wrong!");
}
}
问题是i
函数的范围内没有check
变量。如果要比较答案,则必须知道数组中的正确位置。
一种选择是将i
传递给check
,这将解决您的直接问题。但是,如果您传递期望的答案,那就更好了-这样check
不需要知道问题和答案保存在哪里。因此,将来您可以用更少的更改来不同地表示数据:
var quiz = [
["What is Superman's real name?", "Clarke Kent"],
["What is Wonderwoman's real name?", "Dianna Prince"],
["What is Batman's real name?", "Bruce Wayne"]
];
var score = 0 // initialize score
play(quiz);
function play(quiz) {
for (var i = 0, question, answer, max = quiz.length; i < max; i++) {
question = quiz[i][0];
//also extract the answer to the question
expectedAnswer = quiz[i][1];
userAnswer = ask(question);
check(userAnswer, expectedAnswer);
} // end of main game loop gameOver();
}
function ask(question) {
return prompt(question);
}
//the function now takes both the user and the expected answers to check them
function check(userAnswer, expectedAnswer) {
if (userAnswer === expectedAnswer) {
alert("Correct!");
score++;
} else {
alert("Wrong!");
}
}