Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pulling out a random object of an array in a NodeList

I have this script written

const termList = document.querySelectorAll('.term');
const randomNum = Math.random()*(termList.length-0)+0;
const randomTerm = termList[randomNum];

I want to have randomTerm pull out a random <div> out from that array that has that class. As written however randomTerm when run in the console simply produces undefined.

Do I need to have the NodeList array created by termList be exported into a non NodeList array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

Math.random()*(termList.length-0)+0

Will give you a floating point number, something like 2.0523062186144134.

Use Math.floor to round it down to the nearest integer like so:

const randomNum = Math.random()*(termList.length-0)+0;
const randomTerm = termList[Math.floor(randomNum)];

Also the -0 and +0 are superfluous:

const randomNum = Math.random() * termList.length;
const randomTerm = termList[Math.floor(randomNum)];

Math.floor(Math.random() * termList.length) works because Math.random() is guaranteed to return a value between 0 and less than 1.

So rounding it down will never result in an index that is greater than the array itself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading