在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
}