如何在JavaScript中的嵌套对象中引用对象属性

时间:2019-04-12 23:39:20

标签: javascript jquery

我正在尝试创建一个具有一系列问题和答案的琐事游戏(每个问题都有一个正确的答案,但其他3个答案将以选择格式显示,供用户选择)。

我遇到的问题是我不知道如何最好地构造对象以实现目标。

到目前为止,我已经考虑了以下方法: -创建一个“问题”对象,其中包含一系列问题,正确答案和每个问题的虚拟答案。即

var metricQuestions = {
    q1: {
        question: "What is my name?",
        correctAnswer: "Elizabeth",
        incorrectAnswer1: "David",
        incorrectAnswer2: "Fraser"
    },
    q2: {
        question: "What is my dog's name?",
        correctAnswer: "Annie",
        incorrectAnswer1: "Purple",
        incorrectAnswer2: "Face"
    }
};

这种方法从体力劳动的角度来看很烂,因为当我向用户呈现问题和正确答案时,我无法从一堆随机的“错误”答案中提取信息。感觉效率低下和重复。

-分别为“问题”和“答案”创建单独的对象,并在问题对象内进行引用,该答案对于特定问题是正确的。在语法方面,我无法使它正常工作。

var metricQuestions = {
    q1: {
        question: "What is First Contentful Paint (FCP)?",
        correctAnswerID = (metricAnswers.a1)
    },
    q2: {
        question: "What is Time to Interactive (TTI)?",
        correctAnswerID: a1
    }
};

我也尝试过在metricQuestions对象中将正确的答案设置为字符串,但是当我随机抽取以填充其他倍数时,我面临必须处理答案库中潜在重复项的问题选择选项(以及其他潜在问题)。

-我尝试过的最后一种方法是嵌套方法,其中同一对象内的属性相互引用。从语法上讲,我遇到各种错误“未捕获的SyntaxError:无效的速记属性初始化程序。”

var questionBank = {
    answers: {
        a1: "A lab metric that measures when the main thread is quiet enough to respond to user input.",
        a2: "A field and lab metric that tells when the first pixel is painted on the screen.",
        a3: "Test answer 3.",
        a4: "Test answer 4.",
        a5: "Test answer 5."
    },
    questions: {
        q1: {
        question: "What is First Contentful Paint (FCP)?",
        correctAnswerID = questionBank.answers.a1
        },
        q2: {
        question: "What is Time to Interactive (TTI)?",
        correctAnswerID = questionBank.answers.a2
    },
    }
};

对于多选琐事游戏,我如何最有效地解决一堆问题,并提供相应的正确答案和几个错误答案?

1 个答案:

答案 0 :(得分:3)

您的QuestionBank可以是一个数组,因此您无需知道键(例如q1,q2等)即可轻松获得随机问题。

QuestionBank的每个元素都将是一个带有问题的对象Question,一个正确答案和一系列错误答案,您可以从中选择一些要显示的内容(您可以选择8个,每次选择3个)。像这样:

const QuestionBank = [ { 
                         question: "What is my name?",
                         correctAnswer: "Elizabeth",
                         wrongAnswers: ["David", "John", "Julian", "Eugene", "Robert"]
                       },

                       { 
                         question: "What is my dog's name?"
                         correctAnswer: "Annie",
                         wrongAnswers: ["David", "John", "Julian", "Eugene", "Robert"]
                       }];