javascriptjqueryarraysiterated-function

Iterate over an array of objects only once


$(document).ready(function() {

allQuestions is the array of objects, which role is providing the questions(question), the answers(choices) and the correct response(correctAnswer) for my app.

        var allQuestions = [{question: "If you were a super hero what powers would you have?",
            choices: ["a", "b", "c", "d"],
            correctAnswer:0},

            {question: "Do you have a cherished childhood teddybear?",
                choices: ["e", "f", "g", "j"],
                correctAnswer:0},

            {question: "Whats your favourite non-alcoholic drink?",
                choices: ["i", "j", "k", "l"],
                correctAnswer:0},

            {question: "Are you religious?",
                choices: ["m", "n", "o", "p"],
                correctAnswer:0}];

Next, once my button, with #next id is clicked, the paragraph with id #question should change his text with the next question from the allQuestions array.

The real result? When I clicked on next button, the function iterates over all the questions and it showed the last one only.

I tried to use a solution from stackoverflow, setting a var hasLooped but doesn't work.

        $('#next').click(function(){
            //var hasLooped = false;
            $.each(allQuestions, function(key){

               // if(!hasLooped) {
                    $('#question').text(allQuestions[key].question);
               // }
               // hasLooped = true;
            })
        })
    });

Solution

  • Save index of question in a variable and increment it whenever #next is clicked.

    Write this:

    $(function () {
        var count = 0,
            len = allQuestions.length;
        $('#next').click(function () {
            if (count < len - 1) {
                count++;
                $('#question').text(allQuestions[count].question);
            } else {
                $(this).remove();
        });
    });
    

    fiddle