[JS] How to have a randomized number correspond to a element in a Array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

[JS] How to have a randomized number correspond to a element in a Array?

When the document loads, I would like a function to be called that will summon a random number from 1 to the length of the Array. With that number I would like it to correspond to an element from the Array. i.e if the random is six, and the sixth element in the Array should be selected.

31st Oct 2019, 5:50 PM
Oswaldo De Los Santos
Oswaldo De Los Santos - avatar
1 Answer
+ 7
To select a random element from a array: arrName[Math.floor(Math.random()*arrName.length)] to select a random number between 0 and your array's length: Math.floor(Math.random()*arrName.length) ==================================== Math.random() - random number between 0 and 1
31st Oct 2019, 6:23 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar