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

//利用洗牌算法
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));

posted on 2017-05-02 18:11  _chuck  阅读(233)  评论(0编辑  收藏  举报

导航