I'm putting together an online quiz and would like to construct many questions. I've made a class constructor (see below). And I've set up variables for input, which are different for each question. I'd like to iterate through their construction but I don't see how to loop through and increase the object names (eg, q1, q2, etc.) and arguments that I pass (eg, answer0, answer1, etc.) using the constructor. Any help would be very appreciated. I think it makes sense if you look at the code below. I know there must be a more efficient way.
let quest = []; //array of question objects
//question constructor
class Question {
constructor(question, answer, hint, icon, congrats, image, location) {
this.answer = answer;
this.congrats = congrats;
this.hint = hint;
this.icon = icon;
this.image = image;
this.location = location;
this.question = question;
this.pushToQuest = function () {
quest.push(this);
};
this.pushToQuest();
}
}
// Question 0 input (actual text removed)
let question0 = "?";
let answer0 = ["", "", "", "", ""];
let hint0 = ["", "", "", "", ""];
let icon0 = "fa-utensils-alt";
let image0 = "img/001.jpg";
let congrats0 = "That's right.... ";
let location0 = '';
const q0 = new Question(
question0,
answer0,
hint0,
icon0,
congrats0,
image0,
location0
);
A possible solution will be to create a json file containing a list of question objects like this
[
{
"question": "some question",
"answer": ["", "", "", "", ""];
"hint": ["", "", "", "", ""];
"icon": "fa-utensils-alt";
"image": "img/001.jpg";
"congrats": "That's right.... ";
"location": "";
},
{
"question": "some question",
"answer": ["", "", "", "", ""];
"hint": ["", "", "", "", ""];
"icon": "fa-utensils-alt";
"image": "img/001.jpg";
"congrats": "That's right.... ";
"location": "";
}
]
And then fetch the data, and use a for each loop on it to create a constructor and append each constructor to the quest list
async function (fetchedJson) {
fetchedJson.forEach((item) => {
const que = new Question(
item.question,
item.answer,
item.hint,
item.icon,
item.image,
item.congrats,
item.location
)
quest.push(que)
})
}
Forgive my code if there are syntax errors because I'm typing with my tablet
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.