본문 바로가기
Javascript

javascript if 및 for문 활용방법

by Antonio Bae 2023. 6. 14.

안녕하세요 for문 안에 if문을 쓰는 것은 개발에서 매우 흔한 일인데 활용하는 방법을 알려드리도록 하겠습니다:)

그 전에 먼저 자바스크립트 데이터 화면 출력 중요 문법을 알려드리겠습니다.

 

HTML은 코딩한 것을 화면에 출력하는 마크업언어 입니다. 

자바스크립트는 프로그래밍 언어로 데이터 등을 출력하려면 관련 명령어를 사용해야 합니다. 

데이터 디스플레이와 관련된 명령어는 아래와 같습니다.

 

● document.write( ) : ()안에 것을 화면에 출력하라는 메서드 

● window.alert() : 경고창을 띄워 ()안의 것을 출력하라는 메서드 

● innerHTML= HTML요소의 내용을 변경하고 싶은 경우에 사용하는 Element오브젝트의 프로퍼티

예를 들어 div요소나 span요소에 작성한 동적으로 내용을 변경할 때 사용할 수 있습니다.

                document.getElementById("id 이름").innerHTML = 변경하고 싶은 내용
 

innerHTML을 사용하기 위해서는 HTML요소에 id 이름을 지정해야 합니다.

 

다음은 i가 5까지 0,1,2,3,4 총 5번을 반복하는 예제입니다.

다음으로 if문을 활용하여 i가 4일 경우, 

html 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let sum = 0;
        for(let i=0; i<5; i ++) {
            sum += i;
            // sum = sum +i;
            if(i==4){
                document.write(i+"=");
            }else {
                document.write(i + "+");
            }
           
        }
        document.write(sum);

    </script>
</body>
</html>

 

Q1. 다음과 같이 코드를 작성해라.

0 다음 출력되는 숫자는 1

1 다음 출력되는 숫자는 2

3 다음 출력되는 숫자는 4

4 다음 출력되는 숫자는 5

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        for(let i=0; i<5; i++) {
            if (i !==2) {
                document.write(i + "다음 출력되는 숫자는" + (i+1) +"<br>");
            }
        }
    </script>
</body>
</html>

 

Q2. 짝수만 나오게 하는 박스 만들기

 

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <!-- font-family: 'Dongle', sans-serif; -->
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/xeicon@2.3.3/xeicon.min.css">
    <!-- XEICON 활용 -->
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style-type: none;
            text-decoration: none;
            font-family: 'Dongle', sans-serif;
            font-size: 17px;            
        }
        h3{
            font-size: 3rem;
        }

        .outBox {
            width: 20rem;
            height: 20rem;
            border-radius: 10%;
            background-color: lightsalmon;
            display: flex;
            justify-content: space-evenly;
            align-items: center;
            flex-direction: column;
        }

        #btn {}

        button {
            width: 15%;
            height: 15%;
            background-color: darkgray;
            font-size: 1rem;
            color: white;
        }

        button:active {
            color: red;
        }

        .inBox {
            width: 15rem;
            height: 8rem;
            border-radius: 20px;
            background-color: aliceblue;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    <div class="outBox">
        <h3>짝수만 출력</h3>
        <button id="btn">출력</button>
        <div class="inBox" id="inBox"></div>
    </div>
    <script>
        let btn = document.getElementById("btn");
        // btn id를 들고 오겠다
        let inBox = document.getElementById("inBox");
        btn.addEventListener("click", function () {
            // 클릭기능을 활용하여 btn 기능을 황성화 시키겠다!!
            let result = "";
            for (let i = 0; i <= 10; i++) {
                if ((i % 2) == 0) {
                    // 짝수일때만 출력을 하고 마지막 /를 없애기 위해 if 한번더 넣겠다
                    if (i == 10) {
                        result += i;
                    } else {
                        result += i + "/";
                        // +=은 누적
                    }
                }
            }
            console.log(result);
            inBox.innerHTML = result;
            // inbox안에 result 내용을 넣어줘! 핵심
        });

    </script>
</body>

</html>