Search code examples
javascriptarraysnodelist

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?

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.