为了账号安全,请及时绑定邮箱和手机立即绑定

在 JavaScript 中循环构造函数

在 JavaScript 中循环构造函数

慕莱坞森 2023-11-12 14:28:24
我正在整理一个在线测验,并想提出许多问题。我创建了一个类构造函数(见下文)。我已经设置了输入变量,每个问题的变量都不同。我想迭代它们的构造,但我不知道如何循环并增加我传递的对象名称(例如,q1、q2 等)和参数(例如,answer0、answer1 等)构造函数。任何帮助将不胜感激!我认为如果你看看下面的代码就很有意义了。我知道一定有更有效的方法。let quest = []; //array of question objects//question constructorclass 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);
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

一个可能的解决方案是创建一个包含问题对象列表的 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)

    })

}

如果由于我使用平板电脑打字而出现语法错误,请原谅我的代码


查看完整回答
反对 回复 2023-11-12
  • 1 回答
  • 0 关注
  • 43 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信