-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?

1
  • Should be from 0 to the length of your array - 1. Arrays are zero index based... Commented Feb 19, 2014 at 17:57

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

YOu should round this. Only integers make valid array indexes.
Ok, nevermind, you just added it ;)
You should floor this. wordlist[wordlist.length] is undefined
@danronmoon or change wordList.length to wordList.length - 1.
@danronmoon thanks, I fogot to floor it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.