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

时间:2013-04-03 14:29:28

标签: javascript

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

这是我的阵列:

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;

}

4 个答案:

答案 0 :(得分:3)

您需要将问题索引的范围限定在函数之外,每次单击按钮时都会增加,并在超出数组范围时将其重新分配给0:

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

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

答案 1 :(得分:2)

在此代码中:

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。

答案 2 :(得分:0)

您需要将currentQuestion存储在某处,然后将其增加为onclick

  var singleQuestion = 0;

  function switchQuestion() {

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

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

 }

目前你会在每次点击时将其重置为0,无论如何只根据长度显示第一个或第二个问题

答案 3 :(得分:0)

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

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

简而言之:

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();