New course! Every coder should learn Generative AI!
Try a free lesson+ 4
How do I randomly choose an item in array?
I've tried using Math.random(); with Math.floor(); but it always gives me a number below 1. Is there a way to change this? Thanks!
4 Answers
+ 4
Well, you can use this
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var data = ["Data1","Aditya","random","Value"];
setInterval(function(){
document.write(data[getRandomInt(0,3)]);
},1000);
getRandomInt give you random integer between, 0 to 3. You can change it to your min and max index number of array.
+ 4
Thanks Aditya kumar pandey. It worked. Can I use that code in my next program if I give you credit for it?
+ 3
You can use it. do not need to give credit. But thanks that you like it.
0
multiply the result of Math.random() with size of your array
ex:
size = 10;
random number is a decimal number from 0 to 1
if 10*random number, and get the floor of the result, you have a random number between 0 and 10 that is an random index of your array
to make ensurance that you'll don't any error of indexes, you can return the result of remainder random index dividing by 10(size)