Javascript 在Java脚本中循环使用构造函数
我正在准备一个在线测验,并想提出许多问题。我制作了一个类构造函数(见下文)。我为输入设置了变量,每个问题都有不同的变量。我想迭代它们的构造,但我不知道如何循环并增加使用构造函数传递的对象名(例如q1、q2等)和参数(例如answer0、answer1等)。任何帮助都将不胜感激!我认为如果你看下面的代码,这是有意义的。我知道一定有更有效的方法Javascript 在Java脚本中循环使用构造函数,javascript,loops,constructor,Javascript,Loops,Constructor,我正在准备一个在线测验,并想提出许多问题。我制作了一个类构造函数(见下文)。我为输入设置了变量,每个问题都有不同的变量。我想迭代它们的构造,但我不知道如何循环并增加使用构造函数传递的对象名(例如q1、q2等)和参数(例如answer0、answer1等)。任何帮助都将不胜感激!我认为如果你看下面的代码,这是有意义的。我知道一定有更有效的方法 let quest = []; //array of question objects //question constructor class Ques
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循环创建一个构造函数,并将每个构造函数附加到任务列表中
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)
})
}
如果有语法错误,请原谅我的代码,因为我正在用平板电脑打字没有什么可循环的。你只有一个问题,一个答案。。。一个位置
let questions=[{“q”:“What is….”,“a”:“It is a….”,“hint”:“It is grey”,“icon”:"@mplungjan我已经意识到如果他那样做,那么问题类就没有真正的意义了,因为问题类所做的就是将看起来与之没有太大区别的对象推到任务
数组中,为了澄清,我发布了一个示例,但还有几十个相同格式的问题。@TKoL Yes exactly、 课堂提问没有意义谢谢,这对我的回答很有帮助