在 JavaScript 中循环构造函数

我正在整理一个在线测验,并想提出许多问题。我创建了一个类构造函数(见下文)。我已经设置了输入变量,每个问题的变量都不同。我想迭代它们的构造,但我不知道如何循环并增加我传递的对象名称(例如,q1、q2 等)和参数(例如,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

);


慕莱坞森
浏览 84回答 1
1回答

森林海

一个可能的解决方案是创建一个包含问题对象列表的 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": "";    }]然后获取数据,并使用 foreach 循环创建一个构造函数并将每个构造函数附加到任务列表中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)    })}如果由于我使用平板电脑打字而出现语法错误,请原谅我的代码
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript