JavaScript中实现PHP的打乱数组函数shuffle实例
PHP 里面有个非常方便的打乱数组的函数 shuffle() ,这个功能在许多情况下都会用到,但 javascript 的数组却没有这个方法,没有不要紧,可以扩展一个,自己动手,丰衣足食嘛。
请刷新页面查看随机排序效果。
代码如下:
<script type="text/javascript"> //<![CDATA[ // 说明:为 Javascript 数组添加 shuffle 方法 var shuffle = function(v){ for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }; var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write("A = ", a.join(","), "<br />shuffle(A) = ", shuffle(a)); //]]> </script>
输出结果:
代码如下:
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 给数组添加一个方法:
代码如下:
<script type="text/javascript"> //<![CDATA[ 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(","), "<br />A.shuffle() = ", a.shuffle()); //]]> </script>
相关推荐
strongyoung 2020-07-19
Johnson0 2020-06-08
Bloddy 2020-06-08
adayan0 2020-04-17
snaillup 2019-11-16
飞鸿踏雪0 2019-11-13
adayan0 2019-10-22
tianhouquan 2015-05-19
shuyun00 2013-12-02
微麦PHP 2019-06-26
yanqianglifei 2019-05-02
mbcsdn 2019-05-02
zilianxiaozhu 2018-09-12
RiverCode 2018-08-20
moneycrazy 2018-12-06
vinflyli 2018-09-17
BalaBalaYi 2018-10-19
tansuo 2019-02-04
jimeshui 2019-05-08