TEST&복습

마무리 문제풀이 5

hyejeong3283 2023. 4. 16. 04:25
Thinking is the capital, Enterprise is the way, Hard Work is the solution.
Abdul Kalam
728x90
반응형

문제

자바스크립트를 사용해서 자동으로 복권 번호를 생성해주는 프로그램을 작성하세요.

번호는 중복되면 안되므로 Set을 이용하고, 숫자는 1부터 45까지의 범위 안에 있어야 하며, 6개의 무작위 수를 추출합니다. 버튼을 클릭했을 때 모든 조건을 반영해서 6개의 숫자를 추출하세요.

 

HTML

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로또번호 랜덤</title>
</head>
    <body>
      <div id="container">
        <h1>로또 번호 생성기</h1>   
        <button>추첨</button> 
        <div id="result"></div>
      </div>
    </body>
</html>

 

CSS

<style>
    @import url('https://webfontworld.github.io/suncheon/Suncheon.css');
    #container {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100vh;
      background-color: #b4cff9;
      justify-content: center;
      font-family: "Suncheon";
    }
    h1 {
        color: rgb(15, 67, 104);
        font-size: 40px;
    }
    button {
      width: 200px;
      padding: 20px;
      font-size: 1.2em;
      border-radius: 20px;
      border: 1px solid #aa9e35;
      background-color: #faf2ac;
      color: #29963f;
    }
    #result {
      padding: 20px;
      font-size: 2.8em;
      color: #691ec5;
      padding-top: 40px;
    }
</style>

 

SCRIPT

<script>
    let button = document.querySelector("button");
    let result = document.querySelector("#result");

    function lottoNumber(){
        let randomLotto = new Set();

        for(let i=1; i<=6; i++){
            randomLotto.add(Math.floor(Math.random() * 45) + 1);
        }
        result.innerText = [...randomLotto];
    }
    button.addEventListener("click", lottoNumber);
</script>

추첨 버튼 클릭시 실행하는 함수 lottoNumber를 생성합니다.

button.addEventListener("click", lottoNumber);를 통해 버튼에 클릭 이벤트를 등록합니다.

 

let randomLotto = new Set();

중복된 데이터를 저장하지 않는 배열 변수를 만들어 줍니다.

 

6개의 추첨 번호를 출력하기 위해 for문을 사용해 6번 반복실행하여

.add를 사용하여 randomLotto 변수에 랜덤으로 생성된 숫자를 저장합니다.

숫자를 1부터 시작하므로 랜덤으로 생성된 숫자에 +1을 하여 1부터 시작하도록 설정합니다.

저장된 배열 데이터를 펼침연산자를 통해 result 영역에 출력합니다.