javascript - 简单的 JavaScript 测验数组问题

标签 javascript

我是一名编程新手,正在完成 Treehouse 的测验。我不想只看解决方案,但我被困住了。我想将每个正确的问题存储在一个新数组中,每个错误的问题也存储在一个新数组中,然后打印出来。我的代码会跟踪每个正确和错误的问题,但它只将一个问题保存到每个新数组中,即使多个问题是正确或不正确的。我确信这很简单,但我做错了什么?

var questions = [
  ['How many states are in the United States?', '50'],
  ['How many legs does a spider have?', '8'],
  ['How many continents are there?', '7']
];

function quiz(quizQuestions) {
  var counter = 0;
  
  for (var i = 0; i < questions.length; i++) {
    var answer = prompt(questions[i][0]);
    
    if (answer === questions[i][1]) {
      var correctAnswers = [questions[i][0]];
      counter += 1;
    } else {
      var wrongAnswers = [questions[i][0]];
    }
  }

  print('<h2>You got these questions right</h2>');
  print(correctAnswers);
  print('<h2>You got these questions wrong</h2>');
  print(wrongAnswers);
  
  var printQuestionsRight = '<h3>You got ' + counter + ' questions right</h3>';
  print(printQuestionsRight);
}

function print(message) {
  document.write(message);
}

quiz(questions);

最佳答案

Use array to hold the questions than variable

join()方法将数组的所有元素连接成一个字符串。

var questions = [
  ['How many states are in the United States?', '50'],
  ['How many legs does a spider have?', '8'],
  ['How many continents are there?', '7']
];
var correctAnswers = [];
var wrongAnswers = [];

function quiz(quizQuestions) {
  var counter = 0;
  for (var i = 0; i < questions.length; i++) {
    var answer = prompt(questions[i][0]);
    if (answer === questions[i][1]) {
      correctAnswers.push([questions[i][0]]);
      counter += 1;
    } else {
      wrongAnswers.push([questions[i][0]]);
    }
  }
  print('<h2>You got these questions right</h2>');
  print(correctAnswers.join('<br>'));
  print('<h2>You got these questions wrong</h2>');
  print(wrongAnswers.join('<br>'));
  var printQuestionsRight = '<h3>You got ' + counter + ' questions right</h3>';
  print(printQuestionsRight);
}

function print(message) {
  document.write(message);
}
quiz(questions);

Fiddle Demo

关于javascript - 简单的 JavaScript 测验数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481171/

相关文章:

javascript - 无法修复添加新待办事项的问题

javascript - 如何在 Meteor 中使用数组动态渲染多个模板?

javascript - scrollr.js 动画仅发生在位置固定的元素上

javascript - 使用 jasmine-node 检查正在加载的 Node 模块

javascript - :hover not working in IE6 after DD_belated transparent . PNG修复(帮助?)

javascript - 从浏览器向 Arduino 发送请求具有高延迟

javascript - 为什么我的函数给出错误消息

javascript - url字符串在jquery中被 chop ?

javascript - 单击按钮时的工具提示

javascript - CK 编辑器上未获取数据