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();

你可能感兴趣的:(JavaScript,prototype)