gpt4 book ai didi

javascript - 如何在 javascript 中为 json 对象创建方法?

转载 作者:行者123 更新时间:2023-11-28 00:18:16 25 4
gpt4 key购买 nike

我创建了一个测验,其中每个问题都是一个 Question 对象,该问题具有 print quiestion 等方法。我已将问题添加到 javascript 文件中,但我想将问题移至外部 Json 文件。

但是,我找不到任何文章介绍如何在这种情况下为导入的 Json 对象(问题对象)创建两种方法。下面是使用 getJson 之前使用一个方法获取测验对象的一段代码:

$(function(){

// <-- QUESTION OBJECT -->
function Question(question, choices, correctChoice, userAnswer, type) {

this.question = question;
this.choices = choices;
this.correctChoice = correctChoice;
this.userAnswer = userAnswer;
this.type = type; // either radio buttons or check boxes

// <-- write question method -->
this.writeQuestion = function() {

var questionContent;
questionContent = "<p class='question'>" + (currentQue + 1) + ". " + this.question + "</p>";
var checked = "";

if(this.type === "radio") {

for(var i=0; i < this.choices.length; i++) {

if((i+1) == this.userAnswer)
checked = "checked='checked'";

questionContent += "<p><input class='css-radio' id='radio" + (i+1) + "' " + checked + " type='radio' name='choices' value='choice'></input>";
questionContent += "<label class='css-label' for='radio" + (i+1) + "'>" + this.choices[i] + "</label></p>";

checked = "";
}
}

else {

for(var i=0; i < this.choices.length; i++) {

if ((i+1) == this.userAnswer[i])
checked = "checked='checked'";

questionContent += "<p><input class='css-checkbox' id='checkbox" + (i+1) + "' " + checked + " type='checkbox' name='choices' value='choice'></input>";
questionContent += "<label class='css-label-checkbox' for='checkbox" + (i+1) + "'>" + this.choices[i] + "</label></p>";

checked = "";
}
}

return $quizContent.html(questionContent);
};

最佳答案

您应该创建一个构造函数来接收 json 并使用您提供的 json 定义其中的所有方法,大致如下:

function Question(questionJson) {
var data = questionJson;

//Public "methods" are defined to "this"
this.getCorrectAnswer = function() {
return data.correctAnswer;
};

//Private "methods
var doSomethingCrazy = function() {
return "crazy";
};

this.getSomethingCrazy = function() {
return doSomethingCrazy();
};
}

然后,假设您有一系列问题:

var questions = [
{questionId: '1', correctAnswer: 'a', possibleAnswers: []},
{questionId: '2', correctAnswer: 'a', possibleAnswers: []},
];

你会:

var instances = [];
for (var q in questions) {
instances[q.questionId] = new Question(q);
}

关于javascript - 如何在 javascript 中为 json 对象创建方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266297/

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