본문 바로가기

Javascript/Javascript(2024 version)

Javascript(2) - 연산자, 제어문, 배열, Date 객체, Math 객체, String 객체

728x90
반응형

1) Javascript

   1-1) 연산자

   1-2) 제어문

   1-3) 배열

   1-4) Date 객체

   1-5) Math 객체

   1-6) String 객체

 

 

 

 

 

1) Javascript

1-1) 연산자

02.연산자.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>
    <script>
      /*
            1. 산술 연산자 : +, -, *, /, **, %, ++, --
            2. 대입 연산자 : =, +=, -=, *=, /=, %=
            3. 비교 연산자 : >, >=, <, <=, ==, !=, ===, !==
            4. 논리 연산자 : &&, ||, !
            5. 타입 연산자 : typeof, instanceof
            - instanceof는 객체가 특정 클래스나 생성자 함수의
              인스턴스인지 여부를 확인. 주로 객체 타입 확인에 사용함.
        */

      // 문자열 연산
      let text1 = "홍";
      let text2 = "길동";
      let text3 = text1 + " " + text2;
      console.log(text3);

      let a = 10,
        b = 20;
      let str = a + "와 " + b + "의 \n합계 값은 = " + (a + b);
      console.log(str);

      // template 문자열
      // 변수, 함수 호출, 객체의 속성에 접근 가능
      let template = `${a}와 ${b}의 \n합계 값은 = ${a + b}`;
      console.log(template);

      // 비교 연산
      let num1 = 50;
      let num2 = "50";
      let num3 = 30;
      let num4 = "30";

      console.log(num1 == num2);
      console.log(num1 === num2);
      console.log(num3 !== num4);

      // 논리 연산
      console.log(num1 < num3 || num1 > num3);
    </script>
  </head>
  <body></body>
</html>

 

 

 

1-2) 제어문

03.제어문.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>
    <script>
      // 조건문
      // if 문
      let num = 10;
      if (num < 20) {
        console.log("20보다 작다");
      }

      // 0, null, '', undefined >> false 반환
      if (!0) {
        console.log(0, true);
      }
      if (!null) {
        console.log(null, true);
      }
      if (!"") {
        console.log("공백", true);
      }
      if (!undefined) {
        console.log("undefined", true);
      }

      // switch 문
      let site = prompt("네이버, 다음, 구글 중 즐겨 사용하는 사이트?");

      switch (site) {
        case "네이버":
          document.write('<a href="https://www.naver.com">네이버</a>');
          break;
        case "다음":
          document.write('<a href="https://www.daum.net">다음</a>');
          break;
        case "구글":
          document.write('<a href="https://www.google.com">구글</a>');
          break;
        default:
          alert("보기 중에 없는 사이트입니다.");
      }

      // 반복문
      for (let i = 0; i < 5; i++) {
        if (i % 2 == 0) {
          document.write('<p class="red">반복문' + i + "</p>");
        } else {
          document.write('<p class="blue">반복문' + i + "</p>");
        }
      }

      // for...in 문
      // 객체의 열거 가능한 속성을 순회할 때 사용
      // 1. 배열 사용 시
      let arr = [2, 4, 6, 8, 10];
      for (let i in arr) {
        // i는 첨자(index)를 의미
        console.log(i, arr[i]);
      }

      // 2. 객체 사용 시
      const obj = { a: 1, b: 2, c: 3 };
      for (let key in obj) {
        // key는 객체의 속성을 의미(key)
        console.log(key, obj[key]);
      }

      // for...of 문
      // 배열, 문자열, Map, Set 등 객체를 순회할 때 사용
      // 변수는 해당 순서의 데이터를 의미(Java의 향상된 for 문)
      const array = [10, 20, 30];
      for (let value of array) {
        console.log(value);
      }
    </script>
    <style>
      .red {
        color: red;
      }
      .blue {
        color: blue;
      }
    </style>
  </head>
  <body></body>
</html>

 

 

 

 

 

 

 

1-3) 배열

04.배열.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>
    <script>
      /*
            배열(Array)
            자바스크립트 배열은 순서가 있는 값들의 집합을
            저장하는 변수
            배열은 다양한 데이터 타입의 값을 포함할 수 있으며,
            각 값은 인덱스로 접근 가능함
        */

      let fruits = ["Apple", "Banana", "Cherry"];
      let fruits2 = new Array("Apple", "Banana", "Cherry");

      // 배열 요소 접근
      console.log(fruits[0]); // "Apple"
      console.log(fruits[1]); // "Banana"

      // 배열 요소 수정
      fruits[1] = "Blueberry";
      console.log(fruits);

      // 배열 길이
      console.log(fruits.length); // 3

      // push : 배열의 끝에 요소 추가
      // 배열의 끝에 하나 이상의 요소를 추가
      fruits.push("Melon");
      console.log(fruits);

      // pop : 배열의 끝 요소 제거
      // 배열의 끝에서 요소를 제거하고, 제거된 요소를 반환
      let lastFruit = fruits.pop();
      console.log(lastFruit); // "Melon"
      console.log(fruits);

      // concat : 배열 합치기
      // 두 개 이상의 배열을 합쳐서 새로운 배열을 반환함
      let vegetables = ["Carrot", "Peas"];
      let food = fruits.concat(vegetables);
      console.log(food);
      console.log(fruits);

      // sort : 배열 정렬
      fruits.sort();
      console.log(fruits);

      // reverse : 역 정렬
      fruits.reverse();
      console.log(fruits);

      // forEach : 배열 순회
      // 배열의 각 요소에 대해 함수를 실행
      fruits.forEach((fruit, index) => {
        console.log(`${index + 1}. ${fruit}`);
      });

      // 2차원 배열
      let arr = ["자바", "DB", ["HTML", "CSS", "JavaScript"]];
      console.log("----2차원 배열----");
      console.log(arr[0]);
      console.log(arr[2][0]);

      for (let subject of arr[2]) {
        console.log(subject);
      }

      // 전체 순회
      for (let i = 0; i < arr.length; i++) {
        // 주어진 대상이 배열인지 여부를 확인
        if (Array.isArray(arr[i])) {
          for (let j = 0; j < arr[i].length; j++) {
            console.log(arr[i][j]);
          }
        } else {
          console.log(arr[i]);
        }
      }
    </script>
  </head>
  <body></body>
</html>

 

 

 

1-4) Date 객체

05.Date객체.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>
    <script>
      // Date 객체
      let today = new Date();
      let nowMonth = today.getMonth();
      let nowDate = today.getDate();
      let nowDay = today.getDay(); // 요일 정보를 가져옴(일: 0 ~ 토: 6)

      console.log(nowDate);
      console.log(nowDay);
      console.log(today.getHours());
      console.log(today.getFullYear());
      console.log(today.getSeconds());
      console.log(today.getMilliseconds());
    </script>
  </head>
  <body></body>
</html>

 

 

 

1-5) Math 객체

06.Math객체.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>
    <script>
      /*
            Math 객체
            1) 속성 : PI(원주율), E(오일러 상수)
            2) 메서드
        */

      // Math
      console.log(`원주율: ${Math.PI}`);
      console.log(`오일러 상수: ${Math.E}`);

      // abs() : 절대값
      console.log(`abs(): ${Math.abs(-3)}`); // 3
      console.log(`abs(): ${Math.abs("-2")}`); // 2
      console.log(`abs(): ${Math.abs("Korea")}`); // NaN
      console.log(`abs(): ${Math.abs(null)}`); // 0
      console.log(`abs(): ${Math.abs("")}`); // 0
      console.log(`abs(): ${Math.abs()}`); // NaN
      console.log(`abs(): ${Math.abs(undefined)}`); // NaN

      // ceil(n) : 올림(주어진 숫자보다 큰 정수에 가깝게 올림)
      console.log("----ceil----");
      console.log(Math.ceil(0.95)); // 1
      console.log(Math.ceil(5.0001)); // 6
      console.log(Math.ceil(-0.95)); // -0
      // Javascript에서는 0과 -0을 구분한다!(기억해 둘 것!!)

      // floor(n) : 내림(주어진 숫자보다 가까운 정수에 내림)
      console.log("----floor----");
      console.log(Math.floor(0.95)); // 0
      console.log(Math.floor(5.0001)); // 5
      console.log(Math.floor(-0.95)); // -1

      // trunc(n) : 버림
      console.log("----trunc----");
      console.log(Math.trunc(0.95)); // 0
      console.log(Math.trunc(5.0001)); // 5
      console.log(Math.trunc(-0.95)); // -0

      // round : 반올림
      console.log("----round----");
      console.log(Math.round(0.95)); // 1
      console.log(Math.round(5.0001)); // 5
      console.log(Math.round(-0.95)); // -1
      console.log(Math.round(-5.5)); // -5
      console.log(Math.round(-5.51)); // -6

      console.log("====참고====");
      console.log(0 / 0); // NaN
      console.log(10 / 0); // Infinity
      console.log(10 / 0.0); // Infinity
      // 2진수로 변환하는 과정에서 오차가 발생하기 때문에 아래와 같은 결과가 출력됨!
      console.log(0.1 + 0.2);
      console.log(0.1 + 0.2 === 0.3); // false

      // max
      console.log("====max====");
      console.log(Math.max(1, 5, 3)); // 5
      console.log(Math.max(-1, -5, -3)); // -1

      // min
      console.log("====min====");
      console.log(Math.min(1, 5, 3)); // 1
      console.log(Math.min(-1, -5, -3)); // -5

      console.log("====스프레드 연산자====");
      // 스프레드 연산자는 "..."으로 표시하며, 배열이나 객체를 확장하거나 복사함!
      let arr = [1, 5, 3];
      console.log(Math.max(arr)); // NaN
      console.log(Math.max(...arr)); // 5

      let arr1 = [1, 2, 3];
      let arr2 = [...arr1];
      console.log(arr2);

      // random : 0 이상 1 미만의 난수를 발생시킴
      console.log("====random====");
      for (let i = 0; i < 5; i++) {
        console.log(Math.random());
      }
    </script>
  </head>
  <body></body>
</html>

 

 

 

 

 

1-6) String 객체

07.String객체.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>
    <script>
      // valueOf() : String 객체의 값을 리턴함
      let str = "Hello";
      console.log(str.valueOf());

      // length : 문자열의 길이값을 리턴함
      console.log(str.length);

      // slice() : 시작 인덱스부터 끝 인덱스 직전까지의 값을 반환함
      let str2 = "Hello World";
      console.log(str2.slice(6, str2.length));
      // 끝나는 인덱스 값을 주지 않으면 마지막까지 자른다!
      console.log(str2.slice(6));
      // 음수를 넣으면 뒤에서부터 자른다!
      console.log(str2.slice(-5));

      // subString() : slice() 함수와 비슷함
      console.log(str2.substring(0, 5));
      // 0보다 작은 수는 0으로 취급
      console.log(str2.substring(-5));

      // replace()
      str3 = "Hello World";
      console.log(str3.replace("World", "홍길동"));

      // search() : 해당 문자 인덱스를 반환함
      console.log(str3.search("o"));

      // charAt() : 문자열에서 인덱스 번호에 해당하는 문자를 반환함
      console.log(str3.charAt(4));

      // indexOf() : 문자열에서 왼쪽부터 찾을 문자와 일치하는 문자를 찾아
      //             제일 먼저 일치하는 문자의 인덱스 번호를 반환함
      //             (만일 찾는 문자가 없으면 -1을 반환함)
      console.log(str3.indexOf("Hello"));

      // lastIndexOf() : 문자열에서 오른쪽부터 찾을 문자와 일치하는 문자를 찾아
      //                 제일 먼저 일치하는 문자의 인덱스 번호를 반환함
      //                 (만일 찾는 문자가 없으면 -1을 반환함)
      console.log(str3.lastIndexOf("World"));

      // match() : 문자열에서 왼쪽부터 찾을 문자와 일치하는 문자를 찾아
      //           제일 먼저 찾은 문자를 반환함
      //           (만일 찾는 문자가 없으면 -1을 반환함)
      console.log(str3.match("World"));

      // substr(a, 문자개수) : 문자열에 a 인덱스부터 지정한 문자 개수만큼 문자열을 반환함
      console.log(str3.substr(3, 5));

      // split() : 지정한 문자를 기준으로 문자 데이터를 나누어 배열에 저장하여 반환함
      console.log(str3.split("o"));
    </script>
  </head>
  <body></body>
</html>