Working with random values in Javascript is like leaving in a cave. The only thing you can work with is Math.random() that returns a random number between 0 and 1. If you need a 0 to 10 value – multiply it by 10 (parseInt(Math.random()) or Match.floor(Math.random() * 10)) … That’s all random stuff you have in Javascript.
I needed a shuffling function to randomize one Array’s elements so the only thing was to build one:
// Add new property to javascript array object Array.prototype.shuffle = function() { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; };
Attache it to the Array prototype object so you can access it as object’s own method:
alert([1, 2, 3, 4, 5].shuffle()); alert(['one', 'two', 'three', 'four', 'five'].shuffle());
Do you have any other ideas or functions to improve the randomize process in Javascript?