Es2020 5강 로또추첨기

Ryu·2021년 2월 27일
0
post-thumbnail

함수를 선언하면 동작을 계속 반복하지 않아도 선언한 함수만을 사용하여 중복을 줄여준다.

map : 1:1의 개념으로 배열을 바꾸어준다.

const arr = [1, 2, 3]
arr.map((a)  => {a * 10})
// =>  [10, 20, 30]

Array(45).fill().map((v, i) => i + 1)
v => 어떠한 값
i => 어떠한 값의 자리수

순서도

1~45번호를 랜덤으로 7가지 뽑는법

  • 1~45번까지 번호를 Math.random을 이용하여 랜덤으로 뽑는다.
  • 1~45번까지의 숫자를 랜덤하게 섞은뒤에 앞에서부터 7번까지 자른다.

splice로 수를 꺼내고 []를 붙여야 정확한 값이 꺼내진다.

[1,2,3].splice(1,2) // [1, 2]
[1,2,3].splice(1,2)[0] // 2

sort : 매개변수를 순서대로 정렬시켜준다(숫자순이아니라 사전순으로 정렬한다)

[30, 50, 40, 7].sort()
//(4) [30, 40, 50, 7]

[30, 50, 40, 7].sort((p, c) => {
return p - c});
//(4) [7, 30, 40, 50]

사전순이기 때문에 sort안에 새로운 함수를 넣어주어야 한다

const candidate = Array(45).fill().map((v, i) => i + 1)
const shuffle = [];
while (candidate.length > 0) {
    const random = Math.floor(Math.random() * candidate.length)
    const spliceArray = candidate.splice(random, 1);
    const value = spliceArray[0];
    shuffle.push(value)
}
console.log(shuffle);
const winBalls = shuffle.slice(0, 6).sort((p, c) => p - c);
const bonus = shuffle[6];

console.log(winBalls);
console.log(bonus);

45개의 숫자를 뽑고 그 45개를 랜덤으로 섞은뒤에 7가지 숫자를 뽑아 오름차순으로 정렬한다.
7번째 숫자는 보너스 볼로 구분한다.

const resultTag = document.querySelector('#result');
for (let i = 0; i < 6; i++) {
        const ball = document.createElement('div');
        ball.className = 'ball';
        ball.textContent = winBalls[i];
        resultTag.appendChild(ball);
    }, 1000 * (i + 1));

const bonusTag = document.querySelector('#bonus');
    const bonusBall = document.createElement('div');
    bonusBall.className = 'ball';
    bonusBall.textContent = bonus;
    bonusTag.appendChild(bonusBall);

for문을 이용하여 당첨숫자와 보너스를 구분하여서 반복한다.

function colorize(number, tag) {
    if (number <= 10) {
        tag.style.background = 'red';
        tag.style.color = 'white'
    } else if (number <= 20) {
        tag.style.background = 'grey';
        tag.style.color = 'white'
    } else if (number <= 30) {
        tag.style.background = 'blue';
        tag.style.color = 'white'
    } else if (number <= 40) {
        tag.style.background = 'green';
        tag.style.color = 'white'
    } else if (number <= 45) {
        tag.style.background = 'yellow';
    }
}

새로운 함수를 통해 숫자와 공의 색을 넣어준다.

const resultTag = document.querySelector('#result');
for (let i = 0; i < 6; i++) {
    setTimeout(() => {

        const ball = document.createElement('div');
        ball.className = 'ball';
        colorize(winBalls[i], ball);
        ball.textContent = winBalls[i];
        resultTag.appendChild(ball);
    }, 1000 * (i + 1));
}

const bonusTag = document.querySelector('#bonus');
setTimeout(() => {
    const bonusBall = document.createElement('div');
    bonusBall.className = 'ball';
    colorize(bonus, bonusBall);
    bonusBall.textContent = bonus;
    bonusTag.appendChild(bonusBall);
}, 7000);

또한 숫자를 1초마다 한번씩 나오게 하려면 setTimeout함수를 사용한다.

profile
쓴다.노트.하는동안.공부

0개의 댓글