I've been exploring ways to store random numbers generated by Math.random. I've come up with a solution where I save the numbers in an array, which is then stored in localStorage. My goal is to append each new array of numbers whenever Math.random is used. To see the code I attempted to write, you can check it out here.
var nums = [];
for (var i = 0; i < 5; i++) {
var num = Math.floor(Math.random() * 50);
nums.push(" " + num);
}
console.log(nums);
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "";
localStorage.setItem(name, old + JSON.stringify(data));
}
if (localStorage.num) {
appendToStorage('num', nums);
} else {
localStorage.setItem("num", JSON.stringify(nums));
}
var nums2 = localStorage.getItem("num");
console.log(nums2);
document.getElementById("test").innerHTML = JSON.parse(nums2);
Unfortunately, this setup doesn't seem to be functioning correctly. The console shows an error message saying
Uncaught SyntaxError: Unexpected token [
. This issue seems to be resolved if I remove the JSON.parse
from the getElementById
. However, I prefer to keep it parsed so that the numbers are displayed more clearly. Any suggestions on how I can resolve this?