Skip to content

Instantly share code, notes, and snippets.

@NKid
Last active August 19, 2020 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NKid/8ce356fae804049bd2f3 to your computer and use it in GitHub Desktop.
Save NKid/8ce356fae804049bd2f3 to your computer and use it in GitHub Desktop.
機機亂數
//Method 1
var ary1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Array.prototype.shuffle = function() {
var i = this.length,
j, tempi, tempj;
if(i == 0) return false;
while(--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = this[i];
tempj = this[j];
this[i] = tempj;
this[j] = tempi;
}
return this;
}
ary1.shuffle();
console.log(ary1);
//Method 2
var ary2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
ary2.sort(function() {
return 0.5 - Math.random();
});
console.log(ary2);
//Method 3
Array.prototype.random = function() {
this.sort(function() {
return 0.5 - Math.random();
});
}
var ary3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
ary3.random();
console.log(ary3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment