Javascript 로또 번호 생성하기

2024. 7. 22. 17:56개발/웹 관련

반응형

자바스크립트(Javascript)로 로또 번호 랜덤 생성하는 코드를 만들어 봤습니다. 물론 직접 코딩하지 않고 Copilot으로 생성했습니다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>로또 번호 생성</title>
  <style>
    #lotto {margin-top:20px; font-size:24px; font-weight:bold; color:#333;}
  </style>
</head>
<body>
  <div style="margin:50px 0; text-align:center;">
    <button onclick="generateLotto()">로또 번호 생성</button>
    <div id="lotto"></div>
  </div>
  <script>
    function generateLotto() {
      let numbers = Array.from({length: 45}, (_, i) => i + 1);
      let lotto = [];
            
      for (let i = 0; i < 6; i++) {
        let index = Math.floor(Math.random() * numbers.length);
        lotto.push(numbers[index]);
        numbers.splice(index, 1);
      }

      lotto.sort((a, b) => a - b);
            
      document.getElementById('lotto').innerText = '로또 번호: ' + lotto.join(', ');
    }
  </script>
</body>
</html>

로또 번호 생성 버튼을 클릭하면 중복되지 않은 숫자 6개를 잘 생성해 줍니다.

Array.from으로 배열 생성해도 되지만 미지원 브라우저를 고려한다면 아래처럼 for문으로 배열 생성해도 됩니다.

let numbers = [];

for (let i=1; i<=45; i++) {
  numbers.push(i);
}

코드 복사해서 재미 삼아 한번 해보시기 바랍니다.

 

오늘도 방문해 주셔서 감사드립니다.

 

반응형