0

Possible Duplicate:
How can I return a random value from an array?
Getting random value from an array

If you have an array of:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]

How would I randomly pick an element from this array?

Community
  • 1
  • 1
methuselah
  • 12,766
  • 47
  • 165
  • 315

3 Answers3

2
var randomDay = days[Math.floor(Math.random()*days.length)]
document.write(randomDay);
evilone
  • 22,410
  • 7
  • 80
  • 107
1

You could use

days[Math.floor(Math.random()*days.length)];
0

If you wanted you could make this a generic function of all Arrays, i.e.

Array.prototype.getRandomElement = function () {
    return this[Math.floor(Math.random() * this.length)];
};

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",
    randomDay = days.getRandomElement();
jabclab
  • 14,786
  • 5
  • 54
  • 51