본문 바로가기
Programming/HTML & CSS & JavaScript

js 1일차 - 연산자, 문장, 객체

by yoon9i 2024. 5. 2.

###########################################################################
###########################################################################
4장. 연산자
###########################################################################
1. 산술연산자

+
-
*
/
%

==> + 를 제외한 나머지는 문자열형태의 숫자가 ("10") 자동으로 수치로 변환되어 연산된다.
    + 는 연결이 된다.
==> 자바: 10/3 --> 3
    JS : 10/3 --> 3.3333~

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

<head>
    <title>js05_연산자1_산술연산자</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 산술연산자
        console.log(10 + 3); // 13
        console.log(10 - 3); // 7
        console.log(10 * 3); // 30
        console.log(10 / 3); // 3.3333~ 
        console.log(10 % 3); // 1

        console.log("#############################");

        console.log("10" + 20); // 1020
        console.log("10" - 20); // -10
        console.log("10" * 20); // 200
        console.log("10" / 20); // 0.5
        console.log("10" % 20); // 10
    </script>
</head>

<body>

</body>

</html>




2. 대입연산자

a=b
a+=b
a-=b
a*=b
a/=b
a%=b

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

<head>
    <title>js05_연산자2_대입연산자</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 대입 연산자
        let n = 10;
        let n2 = 5;

        n += n2;
        console.log(n, n2); // 15 5

        n -= n2;
        console.log(n, n2); // 10 5

        n *= n2;
        console.log(n, n2); // 50 5

        n /= n2;
        console.log(n, n2); // 10 5

        n %= n2;
        console.log(n, n2); // 0 5
    </script>
</head>

<body>

</body>

</html>




3. 비교연산자

a==b (같냐? equal 연산자) -> 값만 비교
a===b (같냐? identical 연산자) -> 값과 타입까지 비교

a!=b (같지 않냐?)
a!==b (같지 않냐?)

a>b (크냐)
a>=b (크거냐 같냐)

a<b (작냐)
a<=b (작거나 같냐)

ex>
  // 비교 연산자2 - equal vs identical
  let n = "10";
  let n2 = 10;

  console.log(n == n2); // equal 연산자 (값만 비교) -> true
  console.log(n === n2); // identical 연산자 (값과 타입까지 비교) -> false

  - undefined 비교시에는 반드시 === (identical)를 사용해야 한다.
    이유는 실제는 null 값일지라도 undefined 와 == 비교하면 true 가 반환된다.

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

<head>
    <title>js05_연산자3_비교연산자1</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 비교 연산자1 - 기본
        let n = 10;
        let n2 = 5;

        console.log(n == n2); //  false
        console.log(n != n2); // true
        console.log(n > n2); // true
        console.log(n >= n2); // true
        console.log(n < n2); // false
        console.log(n <= n2); // false
    </script>
</head>

<body>

</body>

</html>

 

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

<head>
    <title>js05_연산자3_비교연산자2</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 비교 연산자2 - equal vs identical
        let n = "10";
        let n2 = 10;

        console.log(n == n2); // equal 연산자 (값만 비교) -> true
        console.log(n === n2); // identical 연산자 (값과 타입까지 비교) -> false

    </script>
</head>

<body>

</body>

</html>

 

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

<head>
    <title>js05_연산자3_비교연산자3_undefined</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // undefined 비교는 반드시 === (identical)로 비교한다.

        let x = undefined;
        console.log(x == undefined);  // true
        console.log(x === undefined);  // true


        let x2 = null;
        console.log(x2 == undefined);
        // true, 실제는 null값일지라도 undefined와 == 비교하면 true 반환됨.
        console.log(x2 === undefined); // false

    </script>
</head>

<body>

</body>

</html>


4. 논리 연산자

&& (and)
|| (or)
! (not)

- 기본형식(1)
논리값 && 논리값 ==> 두개 모두 true 인 경우에 true 반환
논리값 || 논리값 ==> 두개 중 하나만 true 여도 true 반환
!논리값 ==> true 값을 false, false 값을 true 반환


* 주의할점
JS 에서는 true/false 만 논리값으로 사용되지 않는다.
일반값도 논리값으로 사용될 수 있다.

false 로 처리되는 값: 0, "", undefined, null, NaN
true 로 처리되는 값: false 제외한 나머지. 


- 기본형식(2) (※중요)
나중에 React.js 조건부 랜더링에서 사용됨.

일반값1 && 일반값2 (*)
==> 일반값1 이 true 이면 일반값2 반환한다.
    일반값1 이 false 이면 일반값1 반환한다.

일반값1 || 일반값2
==> 일반값1 이 true 이면 일반값1 반환한다.
    일반값1 이 false 이면 일반값2 반환한다.

 

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

<head>
    <title>js05_연산자4_논리연산자</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 논리 연산자
        console.log(true && true); // true
        console.log(true && false); // false
        console.log(false && true); // false
        console.log(false && false); // false
        console.log("####################")
        console.log(true || true); // true
        console.log(true || false); // true
        console.log(false || true); // true
        console.log(false || false); // false
        console.log("####################")
        console.log(!false); // true
        console.log(!true); // false

    </script>
</head>

<body>

</body>

</html>

 

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

<head>
    <title>js05_연산자4_논리연산자1_조건부랜더링</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 논리 연산자
        console.log(10 && "홍길동"); // 홍길동
        console.log(NaN && "홍길동"); // NaN

        console.log(10 || "홍길동"); // 10
        console.log(NaN || "홍길동"); // 홍길동

    </script>
</head>

<body>

</body>

</html>



5. 증감연산자

- 기본 증감연산자
++n;
n++;

--n;
n--;

* 주의할점:
다른 연산자와 같이 사용시 전치/후치에 따라서 결과값이 달라질 수 있다.
ex>
  let result = ++n; // 먼저 1증가 나중에 result 에 할당
  let result = n++; // 먼저 result 에 할당하고 나중에 1증가

 

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

<head>
    <title>js05_연산자5_증감연산자</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 증감 연산자
        // 1. 기본

        let n = 10;
        ++n; // n++;
        console.log(n); // 11

        // 2. 다른 연산자와 같이 사용
        let n2 = 10;
        let result = ++n; // n++;
        console.log(result, n); // 12 12
    </script>
</head>

<body>

</body>

</html>




6. 3항 연산자
- 문법:
     (조건식)?참:거짓;

- 중첩 가능

 

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

<head>
    <title>js05_연산자6_삼항연산자</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 3항 연산자
        let result = (10 > 3) ? 100 : 200;
        console.log(result);
    </script>
</head>

<body>

</body>

</html>

 

###########################################################################
###########################################################################
5장. 문장
###########################################################################

1. 문장종류

문장
- 실행문: 
  순차문
  제어문(조건문- if, if~else, 다중if, switch, 반복문- for, while, do~while, foreach)
  -> switch 문은 내부적으로 === (identical) 을 사용한다.
- 비실행문: 주석문 (// 한줄주석, /* 여러줄주석 */)
- let 변수는 블럭scope 를 갖는다. (자바와 동일한 문법)
  var 변수는 함수scope 를 갖는다.

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

<head>
    <title>js06_문장1_조건문</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 조건문
        // 1. 단일 if 문
        if (3 > 2) {
            console.log("3 > 2");
        }
        if (3 > 2 && 100 % 2 == 0) {
            console.log("3 > 2 && 100 % 2 == 0");
        }

        // 2. if-else 문
        if (3 < 2) {
            console.log("true");
        } else {
            console.log("false");
        }

        // 3. 다중 if 문
        let num = prompt("점수를 입력");
        num = Number.parseInt(num); // "80" --> 80
        // let num = 90;
        if (num >= 90) {
            console.log("A 학점");
        } else if (num >= 80) {
            console.log("B 학점");
        } else if (num >= 70) {
            console.log("C 학점");
        } else {
            console.log("F 학점");
        }

        // 4. switch
        var x = 100;
        switch (x) {
            case 50: console.log("50"); break;
            case 100: console.log("100"); break;
            case 150: console.log("150"); break;
            default: console.log("default"); break;
        } // 100

        // 내부적으로 === (identical) 을 사용한다.
        var x2 = "100";
        x2 = Number.parseInt(x2); // 안할시 default 출력
        switch (x2) {
            case 50: console.log("50"); break;
            case 100: console.log("100"); break;
            case 150: console.log("150"); break;
            default: console.log("default"); break;
        } // default -> 100

    </script>
</head>

<body>

</body>

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

<head>
    <title>js06_문장2_반복문</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 반복문

        // 1. for문
        for (var i = 0; i < 5; i++) {
            console.log("Hello: ", i);
        }

        //2. while문
        var i = 0;
        while (i < 5) {
            console.log("world: ", i);
            i++;
        }

        //3. do~while문
        var i = 0;
        do {
            console.log("happy: ", i);
            i++;
        } while (i < 5);

    </script>
</head>

<body>

</body>

</html>

 

###########################################################################
###########################################################################
6장. 객체(object)
###########################################################################

1. 종류 3가지

==> 자바처럼 상속과 비슷한 개념(프로토타입 관계)으로 계층구조화 되어있음.
    최상위 객체는 Object 이다.
==> 객체의 구성요소는 변수, 메서드(정적메서드-클래스명.메서드(), 인스턴스 메서드), 생성자를 가짐.

1> 데이터(기본+참조) 관련 객체
- 문자관련 ==> String 객체가 관리
- 수치 ==> Number 객체가 관리
- 날짜 ==> Date 객체가 관리
- 배열 ==> Array 객체가 관리
- JSON ==> object 객체가 관리

2> BOM (Browser Object Model)
- 웹 브라우저 관련 객체
- 종류
Window 객체
Screen 객체
History 객체
Location 객체
Navigator 객체


3> DOM (Document Object Model)
- html 문서 관련 객체
- Document 객체


2. 데이터 관련 객체
1> 문자데이터 관련 객체
- String 객체 관리
- 생성방법 3가지

가. 리터럴 값만 이용
let s = "hello";

나. new 생성자 이용
let s2 = new String("hello");

자바:
String s = "hello";
String s2 = new String("hello");

다. 생성자 이용
let s3 = String("hello");

- 문자열 표현방법 3가지
가. 'hello'이용
나. "hello"이용
다. `hello` 이용(백틱, template literal)

* 백틱장점 2가지
1> 변수삽입 가능: ${변수}이용
2> 들여쓰기, 엔터 같은 동작이 그대로 적용되어 출력포맷의 가독성이 높아진다.

- 메서드 조회
http://developer.mozilla.com

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

<head>
    <title>js07_객체1_데이터관련1_String</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 문자열 생성
        let s = "hello"; // string
        let s2 = new String("hello"); // "object"
        let s3 = String("hello"); // string

        console.log(s, s2, s3);
        console.log(typeof s, typeof s2, typeof s3); // string object string

    </script>
</head>

<body>

</body>

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

<head>
    <title>js07_객체1_데이터관련1_String2_문자열표현방법3가지</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        // 문자열 표현식 3가지 방법
        let s1 = 'HeLlo';
        let s2 = "HeLlo";
        let s3 = `HeLlo`;

        console.log(s1);
        console.log(s2);
        console.log(s3);

        // `` 사용 장점1
        // 제공된 변수이용해서 다음과 같이 출력하시오.
        let name = "홍길동";
        let age = 20;

        // 출력포맷
        // 이름: 홍길동 나이: 20

        // 해결1 : ""('') 이용하면 + 사용해서 연결해야 된다.
        let result = "이름:" + name + " 나이:" + age;
        console.log(result);

        // 해결2 : 백틱(`)사용해서 변수를 삽입시켜서 사용가능(권장)
        let result2 = `이름:${name} 나이:${age}`;
        // let result3 = "이름:${}나이:${}"; // " " 는 안됨.
        console.log(result2);

        // `` 사용 장점2
        // 출력포맷
        // <tabe> 태그로 만든 문자열을 출력하시오. 들여쓰기 필요
        /*
            <table>
                <tr>
                    <td>
        */
        // 해결1: ""('') 이용 ==> 해결안됨.
        let table = "<table>";
        table += "<tr>";
        table += "<td>";

        console.log(table);

        // 해결2: 백틱(``) 사용
        let table2 = `<table>
                        <tr>
                            <td>hello</td>
                            <td>${name}</td>
                    `;
        console.log(table2);


    </script>
</head>

<body>

</body>

</html>