[英]looping through constructors in Java Script
我正在整理一个在线测验,并想构建许多问题。 我制作了一个 class 构造函数(见下文)。 我已经设置了输入变量,每个问题都不同。 我想遍历它们的构造,但我不知道如何循环并增加我通过的 object 名称(例如 q1、q2 等)和 arguments (例如 answer0、answer1 等)构造函数。 任何帮助将不胜感激。 如果您查看下面的代码,我认为这是有道理的。 我知道必须有更有效的方法。
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
);
一个可能的解决方案是创建一个 json 文件,其中包含这样的问题对象列表
[
{
"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": "";
}
]
然后获取数据,并使用for each循环在它上面创建一个构造函数和append每个构造函数到任务列表
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)
})
}
如果有语法错误,请原谅我的代码,因为我正在用平板电脑打字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.