cabralpinto
cabralpinto

Reputation: 2098

Pop up with a random string of an array

I'm trying to make an alert box pop up with one random sentence from an array of sentences inside it. This is my code:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) - 1);

alert(tasks[randomTask]);

If you run it, the only thing the pop says is "undefined". Why doesn't it work?

Thanks to anyone that answers! :-)

Upvotes: 0

Views: 590

Answers (3)

Beroza Paul
Beroza Paul

Reputation: 2117

This will do:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var rand = Math.floor(Math.random() * ((tasks.length -1) - 0 + 1)) + 0;
alert(tasks[rand]);

Upvotes: 1

Misa Lazovic
Misa Lazovic

Reputation: 2823

Math.random returns a random number between 0 (inclusive) and 1 (exclusive), you multiply it by 3 and subtract 1, so you can get a number between -1 and 2 (where 2 is exclusive - value will always be lower than 2). And when you floor a negative value, you get -1. That's why you get undefined sometimes

Basically, remove - 1 and it should work

Upvotes: 4

Tushar
Tushar

Reputation: 87203

The reason is that, the Math.random() returns a number between 0 and 1.

When the number is 0.1xxx, it is

computed as

0.1xxxxx * 3 - 1

that is

Math.floor(0.3xxxx - 1) = -1

And array[-1] is undefined.

To get around this issue, you can use % operator on the resulting random number. % will ensure that the number is always between 0 and arr.length - 1.

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) % tasks.length);

alert(tasks[randomTask]);

Upvotes: 2

Related Questions