简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM