Skip to content

Instantly share code, notes, and snippets.

@acoard
Created March 4, 2014 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoard/9341531 to your computer and use it in GitHub Desktop.
Save acoard/9341531 to your computer and use it in GitHub Desktop.
Adds a .randomElement() method to lists by extending Object.prototype
//This little snippet does the bad practice of overloading default JavaScript objects. I know it's bad taste, sue me.
//It only works on arrays.
//['a', 'b', 'c'].randomElement()
Object.prototype.randomElement = function(){
var randomIndex = Math.floor(Math.random() * this.length);
return randomString = this[randomIndex];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment