gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:01:01 24 4
gpt4 key购买 nike

我有一个类:

    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com