简体   繁体   English

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

[英]How can I create methods for json objects in javascript?

I've created a quiz where every question is a Question object which question has methods like print quiestion and so on. 我创建了一个测验,其中每个问题都是一个Question对象,该问题具有诸如打印quiestion之类的方法。 I've added my questions inside the javascript file but I want to move the questions to an external Json file. 我已将问题添加到javascript文件中,但我想将问题移至外部Json文件。

However I can't find any article that covers how two create methods for the imported Json objects (the question objects) in this case. 但是,在这种情况下,我找不到任何一篇文章介绍如何为导入的Json对象(问题对象)创建两个方法。 Here is a piece of code for the quiz object with one method before using getJson: 这是使用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);
    };

You should create a constructor function that receives the json and defines all methods there, using the json you've provided, something rough like this: 您应该使用接收到的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();
    };
}

And then, lets say you have an array of questions: 然后,假设您有一系列问题:

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

You do: 你做:

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

This code worked: 此代码有效:

var allQuestions = [];
var category = "history";

for(var i=0; i < jsonDataLength; i++) {

    allQuestions[i] = new Question(); // create empty question Obj
    var questionNr = "q" + (i+1).toString(); // store questionNr in variable

    for(var properties in jsonData[category][questionNr]) // loop through questionObjs properties
        allQuestions[i][properties] = jsonData[category][questionNr][properties]; 
                     // add them to empty QuestionObj
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为存储在JavaScript数组中的对象创建相同的属性和方法? - How can I create identical properties and methods to objects stored in an array in JavaScript? 我如何创建数量不确定的数组以将JSON对象放入(javascript) - how can i create an undetermined number of arrays to place JSON objects in (javascript) 如何遍历复杂的多级 json 字符串以在 Angularjs 或 Javascript 中创建对象? - How can i traverse a complex multi level json string to create objects in Angularjs or Javascript? 如何使用JavaScript创建此API并分析方法 - How can I create this API with JavaScript and break out the methods 如何在Javascript对象中定义方法? - How do I define methods in Javascript objects? 如何在javascript中模拟对象及其方法 - how do I mock objects and their methods in javascript 如何使用Javascript或Jquery将JSON对象包装在数组中? - How can I wrap JSON objects in an array using Javascript or Jquery? 如何从对象数组创建 JavaScript object? - How can I create a JavaScript object from an array of objects? 使用JavaScript和Firebase,如何创建用户特定的对象? - Using JavaScript and Firebase, how can I create user specific objects? 如何在 JavaScript 中动态创建对象列表? - How can I create a list of objects dinamically in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM