为什么我的检查答案功能会收到错误消息,并且无法从其他功能到达变量数组?

问题描述 投票:0回答:1
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!");
  }
}
javascript arrays function global-variables
1个回答
0
投票

问题是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!");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.