比较不同阵列所需的解决方案

时间:2019-07-13 20:49:20

标签: javascript jquery

我将如何比较一系列问题,例如var questions = ["q1", "q2"] 布尔答案的答案数组,例如var answers = ["false", "true"] 真正的错误是单选按钮。

我一直在寻找解决方案,但没有发现任何问题。

var questions = [
  "The Flag has 50 stripes.",
  "The Statue of Liberty is in NY City.",
  "Betsy Ross wrote the Star Spangled Banner.",
  "The Man from Uncle was really his cousin.",
  "Anne Margaret is the BOMB."
];

var answers = ["false", "true", "false", "false", "true"];

我希望在单击问题1的错误按钮时,获胜次数的更新将增加1。

1 个答案:

答案 0 :(得分:1)

您只需要将问题索引与同一索引处的答案数组的元素进行比较。下面是一些简单的代码,涵盖了您的测验。

let i = 0;
let winCount = 0;

var questions = [
  "The Flag has 50 stripes.",
  "The Statue of Liberty is in NY City.",
  "Betsy Ross wrote the Star Spangled Banner.",
  "The Man from Uncle was really his cousin.",
  "Anne Margaret is the BOMB."
];

var answers = ["false", "true", "false", "false", "true"];

function nextQ(answer) {
  if (answer) checkAnswer(answer);
  if (i >= questions.length) {
    return getResult();
  }
  document.getElementById('q').innerText = questions[i++];
}

function checkAnswer(answer) {
  if (answers[i - 1] === answer) winCount += 1;
}

function getResult() {
  const el = document.getElementById('res');
  el.innerText = `You have ${winCount} correct answers!`;
  el.style.visibility = 'visible';
  document.querySelectorAll('#q, button').forEach(e => e.style.display = 'none');
}

document.querySelectorAll('button').forEach(btn => {
  btn.addEventListener('click', e => nextQ(e.target.dataset.val))
})

nextQ();
#q {
  font-size: 1.2em;
  font-weight: 600;
  margin-bottom: 1rem;
}

#q:after {
  content: '?';
}

#res {
  color: red;
  font-size: 1.5em;
  font-weight: 600;
  background: #c0c0aa;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #1cefff, #c0c0aa);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #1cefff, #c0c0aa);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  visibility: hidden;
}
<div id="q">

</div>
<button data-val="true">
  True
  </button>
<button data-val="false">
  False
</button>
<div id="res">

</div>

请注意,"false"是字符串,而不是布尔值。