2009年11月3日 星期二

[Javascript] 以 Array 方式產生亂數序列

有時需要一串亂數序列使用時,例如亂數播放影片等等的,就可以用下面這招!把數列都打亂囉。


使用到 Math.round (四捨五入) 與 Math.random (亂數),流程是先呼叫 Math.random 產生一個介於 0 ~ 1 的數字,再利用 Math.round 讓這個數值為 0 或 1 ,最後再把數值扣 0.5 ,讓它明確地變成負數或正數,以此達成 sorting 用的 compare function 啦。因此呼叫 sort 完後,就變成亂數的序列囉。


<script type="text/javascript">
    test = new Array( 1 , 2 , 3 , 4 , 5 );
    test.sort( function(){ return Math.round( Math.random() ) - 0.5 ; } );
    document.write( test );
</script>

參考資料



沒有留言:

張貼留言