Stack/JavaScript

[JS] 조건문 2

7ingout 2022. 4. 28. 10:05

if(조건) {

    조건이 맞을 때 실행

} else {

    조건이 맞지 않을 때 실행

}

if(조건1){

     조건1이 true 일 때 실행

} else if(조건2) {

     조건1이 false고 조건2가 true일 때 실행

} else {

    조건1이 false고 조건2도 false일 때 실행

}

 

조건이 

let num = 0

if(num ===1) {

 

} else if(num ===2) {

 

}else if(num ===3) {

 

} else if(num ===4) {

 

} else if(num ===5) {

 

} else {

 

}

switch(num){

    case 1:

    실행문;

    case2:

    실행문;

    break;

    case 3:

    실행문;

    break;

    default:

    실행문;

}

switch(매개변수){

    case '0':

    실행문;

    break;

    case '1':

    실행문;

    break;

    default:

    실행문;

}

 

삼항조건식

구문 (조건) ? 참일 때 실행: 거짓일 때 실행;

(5<15) ? alert(true) : alert(false);

 

(inputColor === "red" || inputColor === "green" || inputColor === "blue") ?
document.querySelector('#color').style.background = inputColor:
document.querySelector('#color').style.background = '#fff';

 

조건문

1. if문

if(조건) {

    조건1이 참일 때 실행

} else if(조건2) {

    조건1이 거짓이며 조건2가 참일 때 실행

} else {

    조건1과 조건2가 둘다 거짓일 때 실행

}

 

2. switch문

switch(variable){

    case 'a':

        variable의 값이 'a'일 때 실행

        break;

    case 'b':

        variable의 값이 'b'일 때 실행;

        break;

    default:

        다 아닐 때 실행;

}

 

3. 삼항조건식

(조건) ? 참일 때 실행 : 거짓일 때 실행 ;

 

let age = Number(prompt("당신의 나이를 입력하세요"));
if(age >= 20) {
    console.log('성인입니다.');
} else {
     console.log('성인이 아닙니다.')
}
age >= 20 ? console.log('성인입니다.') : console.log('성인이 아닙니다.');  

 

let result;

if ( a + b < 4) {

     result='미만';

} else {

     result='이상';

}

a + b < 4 ? console.log('미만') : console.log('이상');

a + b < 4 ? result = '미만' : result = '이상';

result = a + b < 4 ? '미만' : '이상';

 


 

20switch.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let num = prompt('1~5까지 숫자를 입력해주세요');
        switch(num){
            case '1':
                console.log('1입니다.');
                break;
            case '2':
                console.log('1입니다.');
                break;
            case '3':
                console.log('3입니다.');
                break;
            case '5':
                console.log('4입니다.');
                break;
            case '5':
                console.log('5입니다.');
                break;
            default:
                console.log('1~5까지의 숫자가 아닙니다.');
        }
        let today = new Date();
        let year = today.getFullYear();
        let month = today.getMonth()+1; // getMonth()는 항상 +1을 해줘야 함
        let date = today.getDate();
        let day = today.getDay(); // 0 1 2 3 4 5 6 일 월 화 수 목 금 토
        // switch(day) {
        //     case 0:
        //     day = '일요일';
        //     break;
        //     case 1:
        //     day = '월요일';
        //     break;
        //     case 2:
        //     day = '화요일';
        //     break;
        //     case 3:
        //     day = '수요일';
        //     break;
        //     case 4:
        //     day = '목요일';
        //     break;
        //     case 5:
        //     day = '금요일';
        //     break;
        //     case 6:
        //     day = '토요일';
        //     break;
        // }
        
        if ( 0 == day) {
            day = '일요일';
        } else if ( 1 == day) {
            day = '월요일';
        } else if ( 2 == day) {
            day = '화요일';
        } else if ( 3 == day) {
            day = '수요일';
        } else if ( 4 == day) {
            day = '목요일';
        } else if ( 5 == day) {
            day = '금요일';
        } else if ( 6 == day) {
            day = '토요일';
        }

        console.log(`연도는 ${year}이고 
        달은 ${month}이고 
        일은 ${date}이고 
        요일은 ${day}이다.`);
        console.log('연도는 ' +year+'이고 달은 '+month+'이고 일은 ' +date+ ' 요일은 ' +day+'이다.')

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

 

21_ex_t.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        li { list-style: none; }
        body > div {
            width: 70%;
            margin: 100px auto;
            background: #eee;
            border-radius: 10px;
            text-align: center;
            padding: 80px;
            line-height: 1.6;
        }
        h2 {
            padding: 30px;
            border-bottom: 1px solid #ccc;
            margin-bottom: 30px;
        }
        #moneyView {
            line-height: 50px;
            font-weight: bold;
        }
        button {
            border: 0;
            outline: 0;
            background: blueviolet;
            color: #fff;
            padding: 10px 20px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div>
        <h2>화면</h2>
        <ul>
            <li>A음료수 : 500원</li>
            <li>B음료수 : 700원</li>
            <li>C음료수 : 1000원</li>
        </ul>
        <div id="moneyView">현재금액: 0원</div>
        <p>
            <button id="btn100">100</button>
            <button id="btn500">500</button>
            <button id="btn1000">1000</button>
        </p>
    </div>
    <script>
        // 버튼을 변수에 담기
        let btn100 = document.querySelector('#btn100');
        let btn500 = document.querySelector('#btn500');
        let btn1000 = document.querySelector('#btn1000');
        let moneyView = document.querySelector('#moneyView');

        let money = 0;

        // 버튼을 클릭하면 1. money가 증가
        // 2. 잔액을 표시
        // 3. 살 수 있는 음료수는 경고창에 표시
        btn100.addEventListener('click', function(){
            money = money + 100;
            moneyView.innerHTML = `현재금액: ${money}원`;
            comparison();
        });
        btn500.addEventListener('click', function(){
            money = money + 500;
            moneyView.innerHTML = `현재금액: ${money}원`;
            comparison();
        });
        btn1000.addEventListener('click', function(){
            money = money + 1000;
            moneyView.innerHTML = `현재금액: ${money}원`;
            comparison();
        });
        function comparison() {
            if (money >= 1000) {
                alert('A, B, C 음료수 선택가능 !')
            } else if(money >= 700) {
                alert('A, B음료수 선택가능 !')
            } else if(money>=500) {
                alert('A음료수 선택가능 !')
            } else {
                alert('선택가능한 음료수가 없음 !')
            }
        }
    </script>
</body>
</html>

 

22_ex_t.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        #wrap {
            width: 60%;
            height: 100vh;
            margin: 50px auto;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        #color {
            width: 300px;
            height: 300px;
            background: red;
            border: 3px solid #333;
            margin-bottom: 20px;
        }
        input {
            width: 220px;
            height: 30px;
            border: 1px solid #ccc;
            outline: 0;
        }
        button {
            width: 70px;
            background: violet;
            color: #fff;
            height: 30px;
            border: 0;
            outline: 0;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div id="wrap">
        <div id="color"></div>
        <div>
            <input type="text" id="input"><button>선택</button>
        </div>
    </div>
    <script>
        // button을 클릭하면
        // input의 값을 받아옴
        // input의 값이 red, green, blue일 때만 color 아이디를 가진
        // div 배경색을 해당하는 값으로 변경
        // 다른 색일 때는 하얀색 배경색으로 지정

        document.querySelector('button').addEventListener('click', function(){
            let inputColor = document.querySelector('input').value;

            // if(inputColor === "red" || inputColor === "green" || inputColor === "blue") {
            //     document.querySelector('#color').style.background = inputColor;
            // } else {
            //     document.querySelector('#color').style.background = "#fff";
            // }



            // switch(inputColor){
            //     case 'red':
            //         document.querySelector('#color').style.background = inputColor;
            //         break;
            //     case 'green':
            //         document.querySelector('#color').style.background = inputColor;
            //         break;
            //     case 'blue':
            //         document.querySelector('#color').style.background = inputColor;
            //         break;
            //     default:
            //         document.querySelector('#color').style.background = '#fff';
            // }


            
            (inputColor === "red" || inputColor === "green" || inputColor === "blue") ?
            document.querySelector('#color').style.background = inputColor:
            document.querySelector('#color').style.background = '#fff';



            document.querySelector('input').value = "";
        });
    </script>
</body>
</html>