Javascript Array shuffle in-place
It works with Array types. The example is a simple list of numbers, but the array could contain anything; lists of strings, functions, DOM nodes, whatever. Unfortunately, a lot of things that seem like arrays in the DOM aren't really, so you can't shuffle the images on a page with just document.images.shuffle() all by itself.
(function () {
var swapper =
function (a,L,e) {
var r = Math.floor(Math.random()*L);
var x = a[e];
a[e] = a[r];
a[r] = x;
};
Array.prototype.shuffle =
function () {
var i,L;
i = L = this.length;
while (i--) swapper(this,L,i);
};
})();
// example
var x = [0,1,2,3,4,5,6,7,8,9];
x.shuffle();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.