简体   繁体   中英

Iterating through dictionary inside class object in JavaScript

I have a class:

    class Quizer {
        // construct new quiz for unique user
        constructor(quizObj) {
            this.quiz = quizObj;
            this.currentQuestionNum = 0;
            this.userSelections = [];
        }
        ...

    buttonAction(setup) {
        //var text = this.quiz.question1.question; <-- //works
        var text = this.quiz[currentQuestionNum].question; // doesnt work
    }
}

That is constructed here:

var quiz = new Quizer(questionObjects);

Where questionObjects is:

var questionObjects = {
    question1: {
        question: "Darwin explained his theory of evolution in a book called?",
        choices: [
            "this is the correct answer, choose me!",
            "On the Origin of Species",
            "Survival of the Fittest"
        ],
        correctAnswer: "On the Origin of Species"
    },

    question2: {
    ...
    }
}

In buttonAction, my goal is to iterate through questionObjects and get each question. Can someone help me with the syntax?

You need something like this

for(var key in questionObjects){
    // The following gives you the question for the current key
    questionsObjects[key].question
} 

As it is stated here :

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

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