显示数组中的下一个对象值

Display next object value in array

本文关键字:一个对象 数组 显示      更新时间:2023-09-26

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

这是我的数组:

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"
}];

当按下按钮时,我希望显示下一个"question"实例。

下面是切换问题的函数:

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;
}

在此代码中:

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

=代替==赋值:

if (singleQuestion >= allQuestions.length) {
    singleQuestion = 0;
} else {
    singleQuestion = singleQuestion + 1; // increment
}

这个增量也可以用这个简短的形式来实现:

singleQuestion++;

整个表达式也可以用模数计算代替:

singleQuestion = (singleQuestion + 1) % allQuestions.length;

最后,变量singleQuestion必须在函数外部定义。

您需要将currentQuestion存储在某个地方,然后将其增量为onclick

  var singleQuestion = 0;
  function switchQuestion() {
  if(singleQuestion >= allQuestions.length) {
      singleQuestion == 0;
   } else {
    singleQuestion +=1; 
   }
document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
 }

目前你会重置它回到0在每次点击不管,只显示第一个或第二个问题基于长度

下面是一个JSFiddle示例,它显示了脚本的可能实现。

我建议只用一个全局对象。
.createElement()代替.innerHTML()

简而言之:

var myGlobalVar = {
    singleQuestion: 0,
    nextButton: document.getElementById("nextQstBtn"),
    questionHolder: document.getElementById("questionHolder"),
    allQuestions: [qstObjOne, qstObjTwo, qstObjThree],
    switchQuestion: function () {
        myGlobalVar.singleQuestion += 1;
        if (myGlobalVar.singleQuestion === myGlobalVar.allQuestions.length) {
                myGlobalVar.singleQuestion = 0;
        }
        myGlobalVar.showQuestion(myGlobalVar.singleQuestion);
    },
    showQuestion: function (qstNum) {
        // Implementation
    },
    init: function () {
        // Script initialisation
        // Attaching events, etc.
};
myGlobalVar.init();