Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中遍历类对象内的字典_Javascript_Loops_Object_Dictionary - Fatal编程技术网

在JavaScript中遍历类对象内的字典

在JavaScript中遍历类对象内的字典,javascript,loops,object,dictionary,Javascript,Loops,Object,Dictionary,我有一门课: class Quizer { // construct new quiz for unique user constructor(quizObj) { this.quiz = quizObj; this.currentQuestionNum = 0; this.userSelections = []; } ... buttonAc

我有一门课:

    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
    }
}
其中,问题对象是:

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: {
    ...
    }
}

在buttonAction中,我的目标是遍历QuestionObject并获得每个问题。有人能帮我弄一下语法吗?

你需要这样的东西吗

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

for…in语句遍历 对象,按任意顺序。对于每个不同的属性,可以使用语句 被处决


为什么不把所有的问题都放到一个数组中呢?然后,您将能够对其进行迭代。如果QuestionObject只包含问题,那么这将起作用。如果它有其他对象,你需要一个条件。很好,但在这种情况下,我认为
questionObjects
只包含问题。是的,我知道这是一个假设,但我认为是这样的。
for(var key in questionObjects){
    // The following gives you the question for the current key
    questionsObjects[key].question
}