Imagine you have an array of numbers.
1 |
var numbers = [1, 2, 3, 5, 6, 20]; |
Goal is to get a random element of an array. There are several solutions posted on stackoverflow.com. But most of them are just too complicated, so I created my solution.
1 2 3 4 5 |
Array.prototype.random = function() { var index = Math.floor(Math.random() * (this.length)); return this[index]; }; |
I have extend Array to add function random. What is does it uses random number and length of array to create a random index. Let’s use it in action.
1 2 |
var numbers = [1, 2, 3, 5, 6, 20]; numbers.random() // will generate 2 in my case |
That’s it. Happy coding.
Update:
Actually it’s very bad practice to extend prototype. Reasons are problems with browser compatibility. It’s better to create a function and use it. Or you can always use libs like underscore and it’s method sample.