请刷新页面查看随机排序效果。
代码如下:
输出结果:
代码如下:
A = 0,1,2,3,4,5,6,7,8,9
shuffle(A) = 1,5,0,9,2,3,6,8,4,7
A.shuffle() = 0,4,2,8,5,1,3,6,9,7
通过prototype 给数组添加一个方法:
代码如下:
//
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
if (!Array.prototype.shuffle) {
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;
};
}
document.write("A = ", a.join(","), "
A.shuffle() = ", a.shuffle());
//]]>
script>