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?

5
  • Though the title of the linked duplicate is jQuery, it's actually pure JavaScript so fit here as well. Commented Dec 8, 2011 at 12:39
  • @ShadowWizard: The title is wrong; I've fixed it. Commented Dec 8, 2011 at 12:41
  • @Tomalak nice, the duplicate link still show the old title though.. hope it's just cache. Commented Dec 8, 2011 at 12:44
  • @ShadowWizard: I don't think the title gets updated in the comments, you'd have to edit it. Commented Dec 8, 2011 at 12:59
  • @Felix Hopefully it will get closed then the comment will be automatically removed.. Commented Dec 8, 2011 at 13:16

3 Answers 3

2
var randomDay = days[Math.floor(Math.random()*days.length)]
document.write(randomDay);
Sign up to request clarification or add additional context in comments.

Comments

1

You could use

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

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.