Javascript로 만드는 로또 번호 추첨기

박상혁·2023년 11월 2일

body 안에 작성한다.

<body>
<script> 
document.write('내용');
</script>
</body>

다른 파일을 연동시키기

<script scr = '파일.확장자'> 
</script>

세미콜론(;) 명령 끝났음을 나타냄
띄워쓰기만 해도 인식함

주석(//) (/**/)

 <script>
        //안녕이라는 글씨를 나타내는 코드
        document.write('안녕');
        document.write('하이');
 </script>

var 변수명 = 값;
let 변수명 = 값;
const 변수명 = 값;

문자열(String)
숫자(int 정수, float 실수)
불(boolean / true, false)

typeof 데이터 (자료형을 알아보는 명령어)

<body>
    <h1>데이터 상자 만들기</h1>
    <script>
        var name = '박상혁'
        var age = 33
        document.write(typeof age) 
    </script>
</body>

로또 번호 추첨기 1

1~45공 중 6개 뽑기

Mate.random();
0이상 1미만 실수(float)

parseInt();
소수점은 버리고 정수로 변환

 <script>
       var num = Math.random()*46;
       var ball1 = parseInt(num);
       document.write(ball1);
   </script>

로또 번호 추첨기 2

배열(Array)

var lotto = [1,2,3,4,5,6];
lotto[0~5] : 배열의 n번째 값

배열명.push('값'); : 배열에 값 추가하기

<script>
        var lotto = [];
        lotto.push(parseInt(Math.random() * 45 + 1));
        lotto.push(parseInt(Math.random() * 45 + 1));
        lotto.push(parseInt(Math.random() * 45 + 1));
        lotto.push(parseInt(Math.random() * 45 + 1));
        lotto.push(parseInt(Math.random() * 45 + 1));
        lotto.push(parseInt(Math.random() * 45 + 1));
        document.write(lotto);
    </script>

로또 번호 추첨기 3

DRY : Don't Repeat Yourself

for 문
for (var i = 0; i<6 ; i++) {반복하려는 코드}

  <script>
        var lotto = [];
        for (var i = 0; i < 6; i++){
            lotto.push(parseInt(Math.random() * 45 + 1));
        }
        document.write(lotto);
    </script>

로또 번호 추첨기 4

로또는 중복되는 숫자가 나올 수 없다
만약 중복이 아니라면 .push()

조건문
if(조건){조건이 참이면 실행되는 코드}
.indexOf(값) : 값이 있으면 1, 없으면 -1

= : 값을 넣는다
== : 값을 비교한다

  <script>
        var lotto = [];
        for (var i = 0; i < 6; i++){
            var num = parseInt(Math.random() * 45 + 1);
            if (lotto.indexOf(num) == -1) {
                lotto.push(num);
            }
        }
        document.write(lotto);
    </script>

로또 번호 추첨기 5

중복되는 숫자가 있는 경우 숫자가 6개가 안뽑힐 때가 있다. 공 6개 뽑을 때까지 반복하게 해야함

while 문
.length : 배열의 길이

  <script>
        var lotto = [];
           while (lotto.length < 6) {
             var num = parseInt(Math.random() * 45 + 1);
                lotto.push(num);
            }
        }
        document.write(lotto);
    </script>

로또 번호 추첨기 6

.sort() : 배열의 값 정렬

1, 2, 3, 11, 22, 33 을 정렬하면
1, 11, 2, 22, 3, 33으로 정렬됨
사전식으로 정렬되므로 아래와 같이 입력하면 숫자가 오름차순으로 정렬됨

.sort((a, b) => a-b) : 숫자 오름차순 정렬


profile
멋진 개발자가 되겠어요 :-)

0개의 댓글