首頁  >  文章  >  web前端  >  JavaScript對陣列進行隨機重排的方法_javascript技巧

JavaScript對陣列進行隨機重排的方法_javascript技巧

WBOY
WBOY原創
2016-05-16 15:49:271150瀏覽

本文實例講述了JavaScript對陣列進行隨機重排的方法。分享給大家供大家參考。具體如下:

這裡提供了兩個方法來對陣列進行隨機重排。

<script>
var count = 100000,arr = [];
for(var i=0;i<count;i++){
 arr.push(i);
}
//常规方法,sort()
var t = new Date().getTime();
Array.prototype.sort.call(arr,function(a,b){ return Math.random()>.5 &#63; -1 : 1;});
document.write(arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);
//以下方法效率最高
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;
  };
}
var t = new Date().getTime();
arr.shuffle();
document.write('<br/>'+arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);
</script>

希望本文所述對大家的javascript程式設計有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn