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

标签 javascript loops object dictionary

我有一个类:

    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/

相关文章:

java - 替换重复的 java 对象,包括所有引用

javascript - Office365 IMAP 访问 : User is Authenticated but not Connected

javascript - 隐藏滚动条/移除滚动条

java - 具有求和功能的 For 循环

java - 多次循环一个方法会导致错误

jQuery - 当鼠标悬停在元素上时如何继续动画?

javascript - 更改事件上的 Firefox jQuery 未按预期工作

javascript - 激活点击后如何找到第 N 个元素

php - 数组中的对象是否通过引用传递?

javascript - 出现 AngularJS Ui-grid 错误