Last active
August 29, 2015 14:03
-
-
Save noel9999/e78296ae57dd10882a1c to your computer and use it in GitHub Desktop.
Javascript: 自己動手做shuffle,隨機置換陣列內的成員
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function shuffle(array){ | |
var myLength = array.length, temp, index | |
while(myLength > 0){ | |
index = Math.floor(Math.random()*myLength); | |
myLength--; //範圍不斷縮減,以防止已改變的成員又做更動 | |
temp = array[myLength]; | |
array[myLength] = array[index]; | |
array[index] = temp; | |
} | |
return array; | |
} | |
//如果要當成物件方法 | |
Array.prototype.shuffle = function (){ | |
var array = this; | |
var myLength = array.length, temp, index | |
while(myLength > 0){ | |
index = Math.floor(Math.random()*myLength); | |
myLength--; | |
temp = array[myLength]; | |
array[myLength] = array[index]; | |
array[index] = temp; | |
} | |
return array; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment