我有两个对象的数组。当用户按下按钮时,我希望显示特定对象属性的下一个值。

这是我的数组:

var allQuestions = [{
    question: "This is question number one",
    choices: ["one", "two", "three", "four"],
    correctAnswer: "two"
}, {
    question: "This is question number two",
    choices: ["dog", "cat", "bear", "lion"],
    correctAnswer: "bear"
}];


当按下按钮时,我希望显示下一个“问题”实例。

这是我关闭问题的功能:

function switchQuestion() {

    var singleQuestion = 0;

    if(singleQuestion >= allQuestions.length) {
        singleQuestion == 0;
    } else {
        singleQuestion == ""; // not sure what should go here
    }

    document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;

}

最佳答案

您需要将问题索引的范围设置在函数之外,每次单击按钮时将其递增,并在数组边界之外将其重新分配回0:

var questionIndex = 0;
function switchQuestion() {
  if(++questionIndex >= allQuestions.length) {
    questionIndex = 0;
  }

  document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
}

10-06 07:45