如何隨機洗牌一個數組
阿新 • • 發佈:2017-08-21
如果 not mode javascrip 處的 temp 但是 org .sh
在使用javascript的時候有可能會有隨機打亂一個數組的需求,我們可以利用數組的sort方法和Math.random來隨機排序
const arr = [1,2,3]; arr.sort(() => 0.5 - Math.random()) console.log(arr)
主要利用了Math.random()生成隨機數與0.5的大小比較來排序,如果0.5 - Math.random()大於或等於0,數組中的兩個數位置不變,小於0就交換位置。
乍一看這樣是達到了隨機排序的效果,但是實際上這個排序是不那麽隨機的。具體分析可以參考這篇文章。
一個更好方式是采用Fisher–Yates shuffle算法,在此處的使用方式如下
const arr = [1,2,3,4,5,6] Array.prototype.shuffle = function() { var i = this.length, j, temp; if ( i == 0 ) return this; while ( --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); temp = this[i]; this[i] = this[j]; this[j] = temp; } return this; } arr.shuffle()
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
如何隨機洗牌一個數組