I want to convert my json file into js array. It works but when I define questions array it does not. Should I leave it like it is? Because in a console I get a error that question is not defined. Should I provide more code(How I display)?
json:
[
{
"question": "Inside which HTML element do we put the JavaScript??",
"choice1": "<script>",
"choice2": "<javascript>",
"choice3": "<js>",
"choice4": "<scripting>",
"answer": 1
},
{
"question": "What is the correct syntax for referring to an external script called 'xxx.js'?",
"choice1": "<script href='xxx.js'>",
"choice2": "<script name='xxx.js'>",
"choice3": "<script src='xxx.js'>",
"choice4": "<script file='xxx.js'>",
"answer": 3
},
{
"question": " How do you write 'Hello World' in an alert box?",
"choice1": "msgBox('Hello World');",
"choice2": "alertBox('Hello World');",
"choice3": "msg('Hello World');",
"choice4": "alert('Hello World');",
"answer": 4
}
]
js:
// with this defined code does not work
let questions = [];
fetch("questions.json")
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
questions = loadedQuestions;
startGame();
})
.catch((err) => {
console.error(err);
});
startGame = () => {
numOfQuestions = 0;
NumBack = 0;
availableQuestions = [...questions];
getNewQuestion();
};
getNewQuestion = () => {
if (availableQuestions.length === 0 || numOfQuestions >= MAX_QUESTIONS) {
//go to the end page
return window.location.assign("/end.html");
}
numOfQuestions++;
console.log(numOfQuestions);
// random question
const questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach((choice) => {
const number = choice.dataset["number"];
choice.innerText = currentQuestion["choice" + number];
});
availableQuestions.splice(questionIndex, 1);
};
Then I use other methods to move.
First with devinition, secound without.