Created
January 6, 2022 08:45
-
-
Save x3r0s/ce6a16f676553ceeef75aa459c80c74e to your computer and use it in GitHub Desktop.
JavaScript Shuffle Prototype
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
// https://im-first-rate.tistory.com/35?category=827433 | |
// Array의 prototype을 지정해주고, shuffle이라는 이름을 가진 함수를 생성 | |
Array.prototype.shuffle = function () { | |
var length = this.length; | |
// 아래에서 length 후위 감소 연산자를 사용하면서 결국 0이된다. | |
// 프로그래밍에서 0은 false를 의미하기에 0이되면 종료. | |
while (length) { | |
// 랜덤한 배열 index 추출 | |
var index = Math.floor((length--) * Math.random()); | |
// 배열의 끝에서부터 0번째 아이템을 순차적으로 대입 | |
var temp = this[length]; | |
// 랜덤한 위치의 값을 맨뒤(this[length])부터 셋팅 | |
this[length] = this[index]; | |
// 랜덤한 위치에 위에 설정한 temp값 셋팅 | |
this[index] = temp; | |
} | |
// 배열을 리턴해준다. | |
return this; | |
}; | |
var array = ["a", "b", "c", "d", "e", "f"]; | |
console.log("섞기전: " + array); | |
array.shuffle(); | |
console.log("1번 섞은후: " + array); | |
array.shuffle(); | |
console.log("2번 섞은후: " + array); | |
array.shuffle(); | |
console.log("3번 섞은후: " + array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment