TIL-16 JS로 로또 추첨기 만들기 !

PRB·2021년 7월 17일
0

JavaScript

목록 보기
10/24
post-thumbnail
<style>
        .ball {
            display: inline-block;
            border: 1px solid black;
            border-radius: 20px;
            width: 40px;
            height: 40px;
            line-height: 40px;
            font-size: 20px;
            text-align: center;
            margin-right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="result">결과 :</div>
    <div id="bonus">보너스 :</div>
    <script>
        let number = Array(45).fill().map((le,index) =>{
            return index + 1    
        })
        let shuffle = []
        while(number.length > 0){
            let random = Math.floor(Math.random() * number.length);
            shuffle.push(number[random]);
            number.splice(random,1);
        }
        let winNumber = shuffle.splice(0,6).sort((a,b) => a-b);
        function colorGood(number,$tag){
            if (number < 10){
                $tag.style.backgroundColor= 'red';
            }   else if (number < 20){
                $tag.style.backgroundColor= 'orange';
            }   else if (number < 30){
                $tag.style.backgroundColor= 'yellow';
            }   else if (number < 40){
                $tag.style.backgroundColor= 'blue';
            }    else{
                $tag.style.backgroundColor= 'green';
            }
        }
        let $result = document.querySelector('#result');
        function drawBall(number, $parent){ 
            let $ball = document.createElement('div');
            $ball.className = 'ball';
            $ball.textContent = number;
            $parent.append($ball)
            colorGood(number,$ball) // $ball을 빼면 오류가 남
        }
        for (let i = 0; i < winNumber.length; i++){
            setTimeout(() => {
                drawBall(winNumber[i], $result)
        }, 1000 * (i + 1));
        }
        let $bonus = document.querySelector('#bonus')
        setTimeout(() => {
            drawBall(shuffle[6], $bonus)
        }, 7000);
    </script>
</body>

알게 된 점

1. 동기 & 비동기

자주 듣던 동기와 비동기를 공부한 건 처음인데 강의를 들어보니 개념은 쉽더라
동기 : 명령어가 위에서 아래로 실행되는 것(순서대로)
비동기 : 특정 명령어의 실행을 끝날 때까지 기다리지 않고 나머지 코드를 먼저 실행

2. 빈 배열 만들기

Array(요소의 개수)

Array(5); // [empty × 5]

3. fill

Array(요소의 개수).fill(채우고싶은 것)

Array(5).fill(1); // [1, 1, 1, 1, 1]

4. map

map을 사용해도 본래 배열은 변하지 않는다.

Array(5).fill(0).map((el,inx) => {
  return inx + 1;
}) // [1,2,3,4,5]

5. sort

메서드 안에 함수를 넣으면 그 함수 규칙대로 배열이 정렬된다.
이런 함수를 비교 함수 라고 한다.

6. setTimeout

setTimeout(() => {
 // 내용
}, 밀리초);

7. slice

slice를 사용해도 원본이 변하지 않는다.
원본을 복사하는 형식

8.appendChild

참고자료
https://www.youtube.com/watch?v=Nw8-BZTrI3c&list=PLcqDmjxt30RvEEN6eUCcSrrH-hKjCT4wt&index=56

profile
사용자 입장에서 사용자가 원하는 것을 개발하는 프론트엔드 개발자입니다.

0개의 댓글