Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

Rainbow

조건문 & 비교 연산자 본문

web/javascript

조건문 & 비교 연산자

kkangsseul1014 2023. 10. 29. 20:43

조건문 

- 주어진 조건에 따라 결괏값을 출력하는 것을 의미

- 조건으로는 비교 연산자나 논리연산자가 사용됨

 

비교 연산자

- 서로 다른 변수와 비교할 때 사용하는 것이다

- true/false 둘 중에 하나의 값을 선택하는 연산자

 불리언(boolean) :예약어 true or false 중 하나의 값으로 사용된다

 

비교 연산자 예시 문제

<h1>comparison operator & Boolean</h1>
    <h2>===</h2>
    <h3>1===1</h3>
    <script>
        document.write(1 === 1);
    </script>

예시 설명 --> 1과 1이 같다면 true 출력한다

 

결과

 

  <h3>1===2</h3>
    <script>
        document.write(1 === 2);
    </script>

예시 설명 --> 1과 2가 같지 않죠 그래서 false가 출력된다

 

 <h3>1&lt;2</h3>
    <script>
        document.write(1 < 2);
    </script>

예시 설명 --> 2가 1보다 크다면 true를 출력한다

결과

 

 <h3>1&lt;1</h3>
    <script>
        document.write(1 < 1);
    </script>

예시 설명 --> 1이 1보다 크지 않죠 값은 false를 출력한다

 

 

 

 

조건문 형식

- if문 뒤에 괄호 안에 불리언(boolean) 값이 true or false로 들어온다

- 조건이 만족하면 true 또는 false라고 한다

 

조건문 문법

 

소스코드

 <h1>Conditional statements</h1>
    <h2>program</h2>
    <script>
        document.write("1<br>");
        document.write("2<br>");
        document.write("3<br>");
        document.write("4<br>");
    </script>

1 ~ 4 줄 바꿈 기능을 써서 출력한다

 

1. 조건이 참 이었을 때

 <h2>if_true</h2>
    <script>
        document.write("1<br>");
        if (true) {
            document.write("2<br>");
            //첫 번째 중괄호 코드 실행되고
        } else {
            document.write("3<br>");
            //두번째 중괄호 코드 무시된다
        }
        document.write("4<br>");
        //마지막 출력된다
    </script>

결과

 

2. 조건이 거짓이었을 때

 <h2>if_false</h2>
    <script>
        document.write("1<br>");
        if (false) {
            document.write("2<br>");
            //첫 번째 중괄호 코드가 무시되고
        } else
            document.write("3<br>");
            //두 번째 중괄호 코드가 실행된다
        }
        document.write("4<br>");
         마지막 출력된다
    </script>

결과

 

조건문의 활용

소스코드

 <h1><a href="index.html">WEB</a></h1>
    <input id="night_day" type="button" value="night" onclick="
    if(document.querySelector('#night_day').value === 'night'){
      document.querySelector('body').style.backgroundColor = 'black';
      document.querySelector('body').style.color = 'white';
      document.querySelector('#night_day').value = 'day';
    } else {
      document.querySelector('body').style.backgroundColor = 'white';
      document.querySelector('body').style.color = 'black';
      document.querySelector('#night_day').value = 'night';
    }
  ">
    <ol>
        <li><a href="1.html">HTML</a></li>
        <li><a href="2.html">CSS</a></li>
        <li><a href="3.html">JavaScript</a></li>
    </ol>
    <h2>JavaScript</h2>
    <p>
        JavaScript (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed,
        prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one
        of the three core technologies of World Wide Web content production. It is used to make webpages interactive and
        provide online programs, including video games. The majority of websites employ it, and all modern web browsers
        support it without the need for plug-ins by means of a built-in JavaScript engine. Each of the many JavaScript
        engines represent a different implementation of JavaScript, all based on the ECMAScript specification, with some
        engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.
    </p>

예시 문제 설명

-  입력한 코드를 넣고 웹 페이지를 열었을 때

1. <input> 태그에 value 속성값이 night가 될 것이고 if를 타고 문서 안의 선택자 아이디 값이 value와 같기 때문에

    body의 backgroundColor를 블랙으로 넣을 것이다 body의 textColor를 화이트로 넣을 것이다

2. 또 한 번 onclick 했을 때 if를 타고 문서 안의 선택자 아이디 값이 night에서 day로 변환되어 있기 때문에

    조건이 맞지 않아 else를 읽고 값을 night로 다시 변환 시킨다

 

리팩토링 : 비효율적인 코드를 효율적이게 만드는 것

소스코드

 

<h1><a href="index.html">WEB</a></h1>
     <input id="night_day" type="button" value="night" onclick="
     var target = document.querySelector('body');
    if(this.value === 'night'){
      target.style.backgroundColor = 'black';
      target.style.color = 'white';
      this.value = 'day';
    } else {
      target.style.backgroundColor = 'white';
      target.style.color = 'black';
      this.value = 'night';
    }
  ">

예시 설명 -->

  this : input에서 자기 자신을 가리킴

- 코드를 짧고 간결하게 쓸 수 있다

var target = document.querySelector('body');
- target으로 지칭

- var 변수명 = 변수target; : 변수를 활용해 간략하게 짧게 사용한다

- 코드가 한줄로 줄어들고 훨씬 간결해진다,유지보수 측면에서 좋다

 

정리 요약

- document.querySelector('#night_day'). value = 'day'; 코드가 버튼을 day로 변환하고
if(document.querySelector('#night_day'). value === 'night') night값을 부정하기 때문에 else 조건에
맞는 설정으로 변경하는 역할을 한다 (else 조건으로)

 

onclick()

※!!※

이벤트는 특정한 동작이나 상황이 발생했을 때 실행되는 코드

onclick은 html요소가 클릭되었을 때  발생되는 이벤트

'web > javascript' 카테고리의 다른 글

(mysqil workbench) 게시판 만들기  (0) 2023.11.05
스키마와 테이블 만들기(mysqli workbench)  (1) 2023.11.04
HTML과 자바스크립트 만남!!  (0) 2023.10.15
아코디언 메뉴 만들기  (2) 2023.09.28
웹 브라우저 Javascript  (0) 2021.12.08