I have a quick question, My project is a quick 4 option answers, With radio buttons and pictures displayed, Now I have the pictures and the answers stored in a text file, That way my JS detects what it reads and then passes it to HTML, Now I use this function to pick a random line:
fetch('./Test.txt', { credentials: 'same-origin', mode: 'same-origin', }) // reads the file as a buffer .then(function(response) { return response.text(); }) .then(function(data) { a = data a = a.toString() // makes the buffer into a readable string a = a.split('n') // makes all the items in the list randomNum = Math.floor(Math.random() * {The number of lines that you have in the text file}) // makes a math equation to get a random line from the text file
Now How would I detect if randomNum
passed a line that was already passed? Or let’s say, How can I check if function randomNum
passed a line that got passed?
Thank you in advance
Advertisement
Answer
Your client-side Javascript code can maintain an array of pictures already seen and store that in a cookie. Execute the following statements inside your function(data) {...}
in the place where you currently have randomNum = Math.floor(...)
:
var picturesSeen = JSON.parse((document.cookie || "a=[]").substring(2)); if (picturesSeen.length === a.length) alert("Sorry, no more pictures"); else { while (true) { var randomNum = Math.floor(Math.random() * a.length); if (picturesSeen.indexOf(randomNum) === -1) { picturesSeen.push(randomNum); break; } } document.cookie = "a=" + JSON.stringify(picturesSeen); }
The cookie will survive a page reload.
You can “reset” the cookie with the command
document.cookie = "a=[]";