码迷,mamicode.com
首页 > 编程语言 > 详细

Javascript 洗牌算法,打乱数组,随机获取元素

时间:2017-05-02 19:43:56      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:this   cti   array   and   his   function   shuffle   元素   prototype   

//利用洗牌算法
Array.prototype.shuffle=function(){
var i,t,m=this.length;
while(m){
i=Math.floor(Math.random()*m--);
t=this[m];
this[m]=this[i];
this[i]=t;
}
return this;
}

var arr=[1,2,3,4,5];
console.log(arr.shuffle());
console.log(arr.slice(0,2));

Javascript 洗牌算法,打乱数组,随机获取元素

标签:this   cti   array   and   his   function   shuffle   元素   prototype   

原文地址:http://www.cnblogs.com/izengbin/p/6797503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!