This code is supposed to get random JSON data from an array when the user clicks the button. I'm using a function to return a random number. But when I load the page and click on the button, sometimes I get random data, while sometimes I get an error.
Why is this? Thanks in advance.
$(document).ready(function () {
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function renderQuiz() {
console.log(userdata.USER.TOPSONGS[(getRandomInt(0,2))][(getRandomInt(0,4))].snippet);
}
...
$('#button').click(function () {
renderQuiz();
console.log("userprogress: " + userprogress);
if (userprogress < 10) {
userprogress++;
$('#answered').text(`${userprogress} / 10`);
}
else { window.location.href = '/result'; }
return;
});
}); //end document.ready
Does userdata.USER.TOPSONGS
contain a 3x5 array in which all values are defined and all values have a .snippet
?
Mostly probably, userdata.USER.TOPSONGS
does not contain [x][y].snippet
for some values 0 <= x <= 2
and 0 <= y <= 4
, causing this error.
Please check your userdata.USER.TOPSONGS
array and/or adjust the minimum and maximum values being passed to the random number function.
Looks like reaching out of the boundaries of the array. Your getRandomInt(min, max)
returns random int including min
and max
values. Check if this is okay.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.