[英]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.