jamiealden1
jamiealden1

Reputation: 23

Looping through nested objects in Javascript

I'm new to Javascript and working on building a quiz app. All of the quiz questions and answers are stored in an array in an object named 'quiz'. I'm trying to use a loop to get the app to cycle through the questions on click of a button. However, the loop I'm using seems to be freezing my page. Any pointers for where I'm going wrong?

//sample object
    quiz = {
        "questions": [
            {
                "question":"Question 1",
                "a":"Answer a1",
                "b":"Answer b1",
                "c":"Answer c1",
                "d":"Answer d1",
            },
            {
                "question":"Question 2",
                "a":"Answer a2",
                "b":"Answer b2",
                "c":"Answer c2",
                "d":"Answer d2",
            }
        ]
    }

//load next question on click   
        $("#next").click(function(){
            for (i=1; i<quiz.questions.length; i.next) {
               $("#question").text(quiz.questions[i].question);
            };
        });

Upvotes: 2

Views: 96

Answers (1)

Quentin
Quentin

Reputation: 943142

for (i=1; i<quiz.questions.length; i.next) {

i.next doesn't modify the value of i. Since i is never modified, the second condition is never not met, so the loop is infinite.

Use i++ instead.


$("#question").text(quiz.questions[i].question);

Each time you go around the loop, you replace the text with the next question. You'll always end up with the last question.

You shouldn't use a for loop if you want to increment each time the button is pressed.

  • Declare i outside the function.
  • Remove the for loop entirely
  • Put i++ at the end of the function
  • Test for when i >= quiz.questions.length and do … whatever you want to do when you run out of questions.

i=1

On the subject of declaring i. JavaScript arrays start at 0. You probably want to initialize it as 0 and not 1.

Upvotes: 4

Related Questions