0

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!

arrogate
  • 15
  • 2

2 Answers2

1

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.

Marco
  • 7,007
  • 2
  • 19
  • 49
0

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

console.log(randomTerm);
<div class="term">foo</div>
<div class="term">bar</div>
<div class="term">baz</div>
<div class="term">foobar</div>
<div class="term">foobarbaz</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71