let finalQuestionList = [];
let questions1 = [];
let questions2 = [];
let questions3 = [];
const QuestionsPerSection = 1;
fetch("questions_1.json")
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
questions1 = loadedQuestions;
})
.catch((err) => {
console.error(err);
});
fetch("questions_2.json")
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
questions2 = loadedQuestions;
})
.catch((err) => {
console.error(err);
});
fetch("questions_3.json")
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
questions3 = loadedQuestions;
// startGame();
})
.catch((err) => {
console.error(err);
});
The above functions is used to fetch questions from a json file and store them in a local variable
generateQuestionsList = () =>{
for (var i = 0; i < QuestionsPerSection; i++) {
let questionIndex = Math.floor(Math.random() * questions1.length);
finalQuestionList.push(questions1[questionIndex])
questions1.splice(questionIndex, 1);
}
for (var i = 0; i < QuestionsPerSection; i++) {
let questionIndex = Math.floor(Math.random() * questions2.length);
finalQuestionList.push(questions2[questionIndex])
questions2.splice(questionIndex, 1);
}
for (var i = 0; i < QuestionsPerSection; i++) {
let questionIndex = Math.floor(Math.random() * questions3.length);
finalQuestionList.push(questions3[questionIndex])
questions3.splice(questionIndex, 1);
}
return 1;
};
After running "generateQuestionsList" in my script, finalQuestionList shows "undefined" as it content. Pls Note. - This function works perfectly when I run it manually in chrome console.
Below is the json file structure [ { "question": "1Inside which HTML element do we put the JavaScript??", "answers": {
"A": "<script>",
"B": "<javascript>",
"C": "<js>",
"D": "<scripting>"
},
"correctanswer": "A"
},
{
"question": "1What is the correct syntax for referring to an external script called 'xxx.js'?",
"answers":{
"A": "<script href='xxx.js'>",
"B": "<script name='xxx.js'>",
"C": "<script src='xxx.js'>",
"D": "<script file='xxx.js'>"
} ,
"correctanswer": "C"
},
{
"question": "1How do you write 'Hello World' in an alert box?",
"answers":{
"A": "msgBox('Hello World');",
"B": "alertBox('Hello World');",
"C": "msg('Hello World');",
"D": "alert('Hello World');"
} ,
"correctanswer": "D"
}
]