New course! Every coder should learn Generative AI!
Try a free lesson+ 1
How to pick a random array member?
I'm trying to make a simple code that picks something random from the array and alerts it to the user.
2 Answers
+ 4
You need to generate a random number from 0 to array.length and use that as an index.
Math.random() will return a number between 0 and 1, so all you need to do is multiply and round down to a whole number.
let random_index = Math.floor(Math.random() * my_array.length);
let my_random_element = my_array[random_index];
+ 13
Here's how to use JavaScript's random() function:
Math.floor((Math.random() * maxValue) + minNumber);
For example, for an array with 100 items:
Math.floor((Math.random() * 100); //Gives 0 - 99