本文實例講述了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 ? -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程序設計有所幫助。
新聞熱點
疑難解答