I'm making a Trivia Game and I'm using The Open Trivia Database to generate 10 random questions.
These 10 questions are separate strings and I want to place them into an array so that I can display them one by one (after the user guesses whether it's True or False.)
Here is the console log of the questions:
Now here is what I'm trying: I have initialized an empty array and then, in the for loop, I'm pushing each question into the array but its not working.
Essentially, what I'm trying to achieve is that when the user clicks a true or false button, the next item in the response will be displayed. I thought an array would work but maybe I'm looking at it in the wrong way.
Any help is appreciated and if I missed something, please let me know. Thank you in advance!
Code:
const api_url =
"https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean";
const triviaQ = document.getElementById("triviaQuestion");
const question_array = []; // this is the empty array
async function getAPI(url) {
const response = await fetch(url);
var data = await response.json();
justQuestions(data);
}
function justQuestions(data) {
/// loop to display all 10 questions
for (let i = 0; i <= 9; i++) {
display_all_questions = data.results[i].question;
current_question = triviaQ.innerHTML = display_all_questions; /// the console log image
let all_questions = question_array.push({ display_all_questions }); //this is where I attempt to add the questions into an array
}
}
First, you are creating a variable 'all_questions' on each iteration and never use it (you don't need it). Second, 'display_all_questions' name is misleading, as it is just the current question.
And finally, your data.results is already the array that you need, so you can just use it like this:
let questions_array = [];
async function getAPI(url) {
const response = await fetch(url);
var data = await response.json();
questions_array = data.results;
console.log(questions_array);
}
Don't forget to handle possible network request errors