Winnie The Pooh Bear 모던자바스크립트 마무리 문제 2 로또번호뽑기

배움기록/JAVASCRIPT

모던자바스크립트 마무리 문제 2 로또번호뽑기

코딩은 처음이라 2023. 4. 16. 19:05

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90
반응형

모던자바스크립트 마무리 문제 2 로또번호뽑기

자바스크립트를 사용해

자동으로 복권 번호를 생성해주는 프로그램 작성하기

 

- 중복되지 않게 set을 사용

- 1~45까지의 범위

- 6개를 무작위로

 

💜 로또번호 뽑기

코드 보기 / 완성 화면

 

 

 

HTML

<div id="wrap">
    <div class="number">
        <h2>로또 번호를 받아가세요!</h2>
        <button class="btn">클릭!</button>
        <div class="result">👆<br>클릭하면 번호가 나옵니다.</div>
    </div>
</div>

클릭버튼과 번호가 나올 구역을 정해줍니다.

 

style

<style>
    @import url('https://webfontworld.github.io/TheJamsil/TheJamsil.css');
    @import url('https://webfontworld.github.io/score/SCoreDream.css');

    * {
        margin: 0;
        padding: 0;
    }
    #wrap {
        margin: 0 auto;
        width: 100%;
        height: 100vh;
        background-color: #FEC5BB;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
    }
    .number {
        font-family: SCoreDream;
        line-height: 30px;
    }
    .number h2 {
        padding-bottom: 20px;
        color: #a74432;
    }
    .btn {
        background-color: #a74432;
        width: 100px;
        height: 100px;
        border-radius: 50px;
        margin-bottom: 10px;
        transition: all 0.6;
        position: relative;
        border-style: none;
        color: #fff;
    }
    .btn:hover {
        transform: scale(1.1);
        background-color: #a74432a0;
    }
    .result {
        color: #000;
        font-size: 17px;
    }
</style>

btn을 hover 했을때 버튼의 크기가 약간 커지도록 transform:scale 속성을 사용했습니다.

 

script

<script>
    const Btn = document.querySelector(".btn");
    const Result = document.querySelector(".result");

    Btn.addEventListener("click", () => {
        let numbers = new Set();

        while(numbers.size < 6) {
            const randomIndex = Math.floor(Math.random() * 45) + 1;
            numbers.add(randomIndex);
        }

        Result.innerHTML = [...numbers].join(", ");
    });
</script>

 Btn.addEventListener("click", ()  => {} ); 요소에 클릭 이벤트가 발생하면 화살표 함수를 실행

numvers 변수에 Set 객체를 할당하고 빈 집합으로 초기화

While(numbers.size < 6) 집합의 크기가 6보다 작을 때까지 반복

const rendomIndex = Math.floor(Math.random() * 45) +1 1부터 45까지의 정수 중 랜덤으로 한개를 생성해 randomIndex 변수에 할당

numbers.add(randomIndex) numbers 집합에 randomIndex 를 추가

Result.innerHHML = [...numbers].join(", " ); 집합을 배열로 변환 Result 요소의 내용으로 설정

반응형