randomElement
I’ll be honest, I’m sympathetic to the view that exending Object.prototype is bad practice. But I’ll be damned if it isn’t conveinent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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]; | |
} |
PROGRAMMING
programming javascript snippet gist