리액트 정리
[로또추첨기] Array methods - Array() fill() map() splice() slice() sort() Math.floor() Math.random() push() pop() 본문
리액트/웹게임
[로또추첨기] Array methods - Array() fill() map() splice() slice() sort() Math.floor() Math.random() push() pop()
버그킴 2020. 2. 27. 06:45로또추첨기 Array 알고리즘
// 45개의 숫자를 랜덤으로 섞은 다음 -> 맨 앞 6개 숫자가 winning number / 맨 뒤 1개 숫자가 bonus number
const candidate = Array(45)
.fill()
.map((v, i) => {
return i + 1;
});
console.log(candidate);
/*
Array(45): 크기 45개짜리 empty 어레이 만들어줌.
fill(): 빈 어레이를 인덱스: undefine 로 전체 채워주기
map():으로 어레이 리턴 (인덱스 값만 추출)
*/
const shuffle = []; // Array(0)
while (candidate.length > 0) {
let randomNum = candidate.splice(Math.floor(Math.random() * candidate.length), 1)[0];
shuffle.push(randomNum);
}
const bonus = shuffle.pop();
const winningNumArr = shuffle.slice(0, 6).sort((a, b) => {
return a - b;
});
console.log('shuffle:', shuffle);
console.log('bonus:', bonus);
console.log('winningNumArr: ', winningNumArr);
결과창 :
[JS] Array 메소드 2
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array Array JavaScript Array 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다. developer.mozilla.or..
bugkim.tistory.com
잊었던 어레이 메소드 !
꼭 유용하게 써먹어라
'리액트 > 웹게임' 카테고리의 다른 글
[로또추첨기] useEffect, useMemo, useCallback 코드부분 + Hooks 코드 완성 + Class 코드 (0) | 2020.02.27 |
---|---|
[틱택토] (in progress) (0) | 2020.02.27 |
[가위바위보] 버튼에 고차함수(High order function) 함수 연달아 쓰기 () => (0) | 2020.02.19 |
[가위바위보] setInterval과 라이프사이클 연동하기 (0) | 2020.02.18 |
[가위바위보] Component Lifecycle (0) | 2020.02.18 |