JavaScript : if 구문, switch 조건문, for 반복문, 구구단 예제

Study/JavaScript

2022.11.29.

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 53



Review


 처음엔 JavaScript 문법이 어렵고 수학이 시작 돼서 이거 내가 할 수 있을까 라는 생각이 들었는데,

생각보다 꽤나 재미지다.

 

CSS보다 좀 더 논리적이고 머리를 써야할 일이 많아서 해결해내면 엄청 쾌감이 든다.

수학을 풀 때는 느끼지 못했는데... 컴퓨터랑 소통하는 기분이 들어서 신난다.

하나하나씩 배워가는 기쁨이 있어서 좋다.

 

요즘은 일을 마치고 나서 밤에 GTQ 시험 준비를 하고 있다.

12월 24일 크리스마스 이브에 내가 나온 대학교 바로 옆에서 시험을 치게 돼서 기분이 묘하다.

시험 일자는 왜 하필 이브인지 껄껄 

원서접수비가 꽤 비싸서 한번에 붙을 각오로 공부하고 있다. 아깝지 않게 ㅎㅎㅎ

  

Pen tool 사용이 제일 어려워서 일러스트 공부를 할 때 고생하고 있다.

학원에서 수업을 들을 때 꽤 연습을 많이 했다고 생각했는데 아직 멀었나보다.

더 열심히 해야지 파이팅 !!!!!!

 

 


 

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 53

 

<modal 창 만들기 예제>

 

- HTML

 

    <button id="btn" onclick="show()">Open modal</button>

    <div id="popup">
        <div class="pop">
            <a href="javascript:void(0)" id="close">닫기</a>
            <p>contents contents contents contents</p>
        </div>
    </div>

 

 

- CSS

 

        @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&display=swap');

        body, button {
            max-width: 1200px;
            margin: 100px auto;

            background: #eee;

            text-align: center;

            font: 18px 'Montserrat', sans-serif;
            font-weight: 500;
        }

        a {
            color: #222222;
        }

        #btn {
            background: #222222;
            color: #fff;

            padding: 10px 20px;
        }

        #popup {
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
        }

        .pop {
            background: #fff;
        }

 

 

- JavaScript

 

    <script>

        let modal = document.getElementById("popup"); 
        let close = document.getElementById("close");

        modal.style.display = "none";

        function show() {
            modal.style.display = "block";
        }

        close.onclick = function() {
            modal.style.display = "none";
        }

     </script>

 

 

0

 


 

<modal 창 만들기 예제>

 

 

- HTML

 

    <button id="btn">Open modal</button>

    <div id="popup">
        <div class="pop">
            <!-- <a href="javascript:void(0)" id="close">닫기</a> -->
            <p>contents contents contents contents</p>
        </div>
    </div>

 

 

- CSS

 

        @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&display=swap');

        body, button {
            background: #eee;

            font: 18px 'Montserrat', sans-serif;
            font-weight: 500;
        }

        #btn {
            background: #222222;
            color: #fff;

            padding: 10px 20px;
            margin: 10px 35px;
        }

        #popup {
            position: fixed;
            left: 250px;
            top: 0;

            width: 100%;
            height: 100%;

            background: rgba(0,0,0,0.5);
        }

        .pop {
            background: #fff;
            padding: 10px;
        }

 

 

- JavaScript

 

    <script>

        let modal = document.getElementById("popup"); 
        let btn = document.getElementById("btn");

        modal.style.display = "none";
        // 만약에 modal 안보이면 보이게하고 보이면 안보이게 해라

        btn.onclick = function() {
            if(modal.style.display == "none") {
                modal.style.display = "block"; 
            } else {
                modal.style.display = "none";
            }
        }

     </script>

 

 

0

 


 

<if 구문 : 아이디, 비번 입력하기 예제>

 

 

- JavaScript

 

    <script>
        let id = "easy";
        let pw = "1234";
        let user_id = prompt("아이디를 입력해 주세요");
        let user_pw = prompt("비밀번호를 입력해 주세요");
        
        /*if(조건) {
            참인실행문;
        } else {
            거짓인 실행문;
        }*/
        
        if(id == user_id) {
            if(pw == user_pw) {
                document.write(user_id+ "님 반갑습니다");
            } else {
                alert("비밀번호가 일치하지 않습니다");
                location.reload();
            }    
        } else {
            alert("아이디가 일치하지 않습니다");
            location.reload();
        }
    </script>

 

0
일치할 때
0
일치하지 않을 때

 


 

 

<if 구문 : 지역, 지역번호 입력하기 예제>

 

 

- JavaScript

 

    <script>

        let area = prompt("지역을 입력해주세요.");
        let area_num;

        if( area == '서울' || area == 'seoul' || area == 's' || "S") {
            area_num = "02";
        } else if(area == '대전' || area == 'daejeon' || area == 'd' || area == 'D') {
            area_num = "042";
        } else if(area == '부산') {
            area_num = "051";
        } else {
            area_num('등록되지 않은 지역입니다.');
        }

        document.write( '입력하신 지역은 ' + area + '이고, 지역번호는 ' + area_num + '입니다.');

    </script>

 

 

012

 


 

 

<if 구문 : 지역, 지역번호 입력하기 예제2>

 

 

- JavaScript

 

    <script>

        let area = prompt( '지역을 입력해주세요.' );
        let area_num;

        switch(area) {
            case "서울" : 
            case "seoul":
            case "Seoul":
            case "s":
            case "S":
                area_num = "02"; 
                area = "서울";
                 break;
            case "대전":
            case "daejeon":     
            case "Daejeon":     
            case "d":     
            case "D":     
                area_num = "042";
                area = "대전";
                 break;
            case "부산":
            case "busan":
            case "Busan":
            case "b":
            case "B":
                area_num = "051";
                area = "부산";
                 break;        
            default: 
                area_num = "등록되지 않은 지역";
                   
        }

        document.write("입력하신 지역은 " + area + "이고, 지역번호는 " + area_num + "입니다.");
        
    </script>

 

 

012

 


 

<switch 조건문 알아보기>

 

 

- JavaScript

 

    <script>

        let week = new Date();
        let weekday = week.getDay(); // 0~6
        
        console.log(weekday);
        
        // 첫 번째 방법
        switch(weekday) {
            case 0:
                document.write("일요일");
                break;
            case 1:
                document.write("월요일");
                break;
            case 2:
                document.write("화요일");
                break;
            case 3:
                document.write("수요일");
                break;
            case 4:
                document.write("목요일");
                break;
            case 5:
                document.write("금요일");
                break;
            case 6:
                document.write("토요일");
                break;     
        }

        //두 번째 방법
        if(weekday == 0) {
            document.write("일요일");
        } else if(weekday == 1) {
            document.write("월요일");
        } else if(weekday == 2) {
            document.write("화요일");
        } else if(weekday == 3) {
            document.write("수요일");
        } else if(weekday == 4) {
            document.write("목요일");
        } else if(weekday == 5) {
            document.write("금요일");
        } else if(weekday == 6) {
            document.write("토요일");
        }
      
    </script>

 

 

 

오늘이 화요일이라서 화요일이라고 출력된다 !

내일 이 파일을 열어보면 수요일이라고 출력될 것이다.

너무 신기하당 -

 

 

 


 

<for 반복문 알아보기>

 

- JavaScript

 

    <script>
        
        let arr = [
        "하나",
        "둘",
        "셋",
        "넷",
        "다섯",
        "여섯",
        "일곱",
        "여덟",
        "아홉",
        "열",
        ];

        let text = "";

        text += arr[0] + "<br>";
        text += arr[1] + "<br>";
        text += arr[2] + "<br>";
        text += arr[3] + "<br>";
        text += arr[4] + "<br>";
        text += arr[5] + "<br>";
        text += arr[6] + "<br>";
        
        document.write(text + "<br>");


        let text2 = "";
        let n = arr.length;
       
        // for(초기값; 조건; 증감값) 
        for( let i = 0; i < n; i ++) {
            // i = i + 1  i 출력 후 +연산을 함
            text2 += arr[i] + "<br>";
        }

        document.write(text2);

    </script>

 

 

 

 

 


 

<for 반복문 : 전역변수>

 

 

- JavaScript

 

    <script>
        let j = ""; // 전역변수 

        for(let i = 1; i <= 10; i ++) {
            j += i + "<br>"; // j = j + i
        }
        
        document.write( j );


        let j2 = ""; 

        for(let i = 10; i >= 1; i --) {
            j2 += i + "<br>"; // j2 = j2 + i
        }

        document.write( j2 );


        let j3 = ""; 

        for(let i = 10; i >= 1; i -= 2) {
            // i = i - 2  i -= 2 
            j3 += i + "<br>"; // j3 = j3 + i
        }

        document.write( j3 );

    </script>

 

 

 

 

 

 

 

 

* 내용 참고 출처

: 자바스크립트 변수의 유효범위 : 네이버 블로그 (naver.com)

 

 

 


 

<for 반복문 : 1부터 100까지의 홀수, 짝수의 합계>

 

 

- JavaScript

 

    <script>
      // 1부터 100까지의 합

      let even = 0;
      let odd = 0;

      for (let i = 1; i <= 100; i++) {
        if (i % 2 == 0) {
          even += i;
        } else {
          odd += i;
        }
      }

      document.write(
        "1부터 100까지 짝수의 합계 : " +
          even +
          "<br>" +
          "1부터 100까지 홀수의 합계 : " +
          odd +
          "<br>"
      );
    </script>

 

 

 

 

 

 


 

 

<for 반복문 예제>

 

 

- JavaScript

 

    <script>
      // 첫 번째 방법
      let arr = [
        "<h6>h6 재미있는 자바스크립트</h6>",
        "<h5>h5 재미있는 자바스크립트</h5>",
        "<h4>h4 재미있는 자바스크립트</h4>",
        "<h3>h3 재미있는 자바스크립트</h3>",
        "<h2>h2 재미있는 자바스크립트</h2>",
        "<h1>h1 재미있는 자바스크립트</h1>",
      ];

      let text = "";

      text += arr[0];
      text += arr[1];
      text += arr[2];
      text += arr[3];
      text += arr[4];
      text += arr[5];

      document.write(text);

      // 두 번째 방법
      for (let i = 6; i >= 1; i--) {
        document.write(
          "<h" +
            i +
            ">" +
            "h" +
            i +
            "재미있는 자바스크립트</h" +
            i +
            ">" +
            "<br>"
        );
      }

      for (let i = 1; i <= 5; i++) {
        document.write('<p style="color: red">' + i + "</p>");
      }
    </script>

 

 

 

 


 

<for 반복문 : 1부터 100까지 홀수와 짝수 색으로 구분하기, 5의 배수와 7의 배수 / 공배수의 색 구분하기>

 

 

- JavaScript

 

    <script>
      for (let i = 1; i <= 100; i++) {
        if (i % 2 == 0) {
          document.write('<a style="color: red">' + i + " </a>");
        } else {
          document.write('<a style="color: blue">' + i + " </a>");
        }
      }

      for (let i = 1; i <= 100; i++) {
        if (i % 5 == 0 && i % 7 != 0) {
          document.write('<p style="color: red">' + i + " </p>");
        } else if (i % 7 == 0 && i % 5 != 0) {
          document.write('<p style="color: blue">' + i + " </p>");
        } else if (i % 5 == 0 && i % 7 == 0) {
          document.write('<p style="color: green">' + i + " </p>");
        }
      }
    </script>

 

 

이건 조금 헷갈렸는데, 생각보다 if 구문에서 신경써야 할 것들이 많았다.

 

5의 배수는 맞지만 7의 배수가 아닌 것, 7의 배수는 맞지만 5의 배수가 아닌 것, 

5의 배수와 7의 배수의 공배수 모두 구분하여 가정해야했다.

 

중딩 때로 돌아간 것 같아서 꽤나 재미지다 :->

 

 

 


 

 

<for 반복문 : 구구단 만들기>

 

- CSS

 

      @import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&display=swap");

      body {
        background: #eee;

        font: 18px "Montserrat", sans-serif;
        font-weight: 500;

        padding: 10px;
      }

      div {
        display: inline-block;
        width: 150px;

        padding: 10px;
      }

 

 

 

- JavaScript

 

    <script>
      document.write("<h2>[ 구구단 ]</h2>");

      let str = "";

      for (let i = 2; i <= 19; i++) {
        str += "<div>";
        str += "<h3>" + i + "단" + "</h3>";
        for (let j = 1; j <= 9; j++) {
          str += i + " X " + j + " = " + i * j + "<br>";
        }
        str += "</div>";
      }

      document.write(str);
    </script>

 

 

 

 

이 예제는 머리에 쥐나는 줄 알았다... 머리를 굴리느라고 흑흑

 

구구단을 만드는 것까지는 쉬웠는데, div 태그를 어떻게 적용시키는지 몰라서 애를 먹었다.

서칭을 해보다가 찾지 못해서 결국 선생님께서 도와주셨당ㅠ_ㅠ 

 

변수를 하나 더 만들어서 document.write() 대신에 변수로 치환해버리고 '+=' 연산자를

넣어주면 된다. 

 

우당탕탕 오늘의 예제 완성 - ! 

반응형