2/20(월) 일단 만드는 JavaScript > [로또 번호 추첨기]

정민지·2023년 2월 21일
0

JavaScritpt를 사용하는 방법

  1. html

  2. js 파일

1. html 파일

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>JavaScript 사용 방법</title>
</head>
<body>
    <h1>JavaScript 사용 방법</h1>
    <script>
        document.write()
    </script>
</body>
</html>
<body> , <script>

안에 쓰고 싶은 말 쓰기

document.write("안녕하세요")

2. js 파일에 명령을 넣어서 html에서 실행

<!-- myScript.js -->
document.write('조코딩 짱짱')
<body>
    <h1>JavaScript 사용 방법</h1>
    <script src="myScript.js"></script>
</body>
 

세미콜론과 주석

자바 스크립트는 엔터 혹은 세미콜론 찍으면 명령어 한줄이 끝났음을 의미

주석: //

여러줄 주석: /* */

데이터 상자 만들기

데이터 상자: 변수

데이터 타입은 명시 안해도 됌

var 변수명 = 값

자료형

문자열: 큰 따옴표 ("") , 작은 따옴표('')로 값 감싸야 함

숫자: 정수형 (int) , 실수형 (float)

불: true, false

let 변수명 = 값

const 변수명 = 값

변수 앞에 typeof 붙히면 값의 자료형이 반환됌

    <script>
        var name = '엄준식';
        document.write(name);
    </script>

로또 번호 추첨기 1

var num = Math.random();

document.write(num); 

Math 클래스의 random 함수가 0 이상 1 미만의 난수를 생성함

=> 만약 내가 원하는 수가 1이상 45 이하 정수라면

Math.random() * 45 + 1 

0 이상 1 미만 * 45 = 0 이상 45 미만 + 1 = 1 이상 46 미만 실수

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

var ball = parseInt(Math.random()*45+1)
document.write(ball)

로또 번호 추첨기 2

로또 볼 6개를 뽑아야 함

배열 이용 - 첫번째 변수는 0번 인덱스 부터 시작

배열변수.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

반복문 - for, while

for (시작;끝;증가){
     반복하려는 코드
}
    <script>
        var lotto = [];
        for (var i = 0; i < 6; i++){
            lotto.push(parseInt(Math.random() * 45 + 1));
        }
        document.write(lotto);
    </script>

로또 번호 추첨기 4

배열에 중복되는 값 제거 - 조건문 사용

if (조건) {

참 일경우 실행 될 명령어

}

.indexOf(값) : 값이 있으면 위치 반환, 없으면 -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

반복문 - for, while 문

while (조건) {
반복하려는 코드
}
.length => 배열의 길이

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

로또 번호 추첨기 6

정렬: sort()

사전순으로 정렬되기 때문에 앞자리가 작은 수가 먼저 나옴

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

숫자 내림차순으로 정렬 = >.sort((a,b)=>b-a))

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

로또 번호 추첨기 최종

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로또 번호 추첨기</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>로또 번호 추첨기</h1>
    <script>
        var lotto = [];
        while (lotto.length < 6) {
            var num = parseInt(Math.random() * 45 + 1);
            if (lotto.indexOf(num) == -1) {
                lotto.push(num);
            }
        }
        lotto.sort((a,b)=>a-b);
        document.write("<div class='ball ball1'>" + lotto[0] + "</div>");
        document.write("<div class='ball ball2'>" + lotto[1] + "</div>");
        document.write("<div class='ball ball3'>" + lotto[2] + "</div>");
        document.write("<div class='ball ball4'>" + lotto[3] + "</div>");
        document.write("<div class='ball ball5'>" + lotto[4] + "</div>");
        document.write("<div class='ball ball6'>" + lotto[5] + "</div>");
    </script>
</body>
</html>
 
profile
꾸준히 성장하는 개발자

0개의 댓글