這篇文章主要介紹了JavaScript對數組進行隨機重排的方法,實例分析了javascript實現數組隨機重新排序的兩種實現技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選