簡體   English   中英

通過JavaScript中的類對象內的字典進行迭代

[英]Iterating through dictionary inside class object in JavaScript

我有一節課:

    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
} 

正如這里所說:

for ... in語句以任意順序迭代對象的可枚舉屬性。 對於每個不同的屬性,可以執行語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM