-5

I need to generate a random number from 0 to the length of my array. This is my array

var wordList = new Array["duck", "cat", "dog", "carpet", "pants", "computer", "book"];

So basically, choose one of these words. then I need to use that number to select that word and print it out. Any help?

dee-see
  • 23,668
  • 5
  • 58
  • 91

1 Answers1

3

Use:

wordList [ Math.floor (Math.random() * wordList.length) ] 

NOTE:

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

The Math.floor() function returns the largest integer less than or equal to a number.

  1. Math.floor MDN Reference
  2. Math.random MDN Reference