我有一个类:
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 quiz = new Quizer(questionObjects);
questionObjects 在哪里:
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 中,我的目标是遍历 questionObjects 并获取每个问题。有人可以帮我解决语法问题吗?
最佳答案
你需要这样的东西
for(var key in questionObjects){
// The following gives you the question for the current key
questionsObjects[key].question
}
如前所述here :
The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
关于javascript - 在 JavaScript 中遍历类对象内部的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36610903/