Skip to content

Instantly share code, notes, and snippets.

@noel9999
Last active August 29, 2015 14:03
Show Gist options
  • Save noel9999/e78296ae57dd10882a1c to your computer and use it in GitHub Desktop.
Save noel9999/e78296ae57dd10882a1c to your computer and use it in GitHub Desktop.
Javascript: 自己動手做shuffle,隨機置換陣列內的成員
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