ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [포스코x코딩온] Javascript 고급(구조분해할당, ...연산자, 클래스)
    [포스코x코딩온] 웹개발자 풀스택 부트캠프8기 2023. 7. 31. 12:07
    728x90

    Javascript 고급

    구조분해 할당 (Destrucring assignment)

    • 배열이나 객체의 속성을 해체해 그 값을 개별변수에 담는 것
    • 배열 구조 분해
    • 객체 구조 분해

    배열 구조 분해

    • const [변수] = 배열;
    • 각 변수에 배열의 인덱스 순으로 값 대응
    • 구조분해 시 변수의 값이 undefined 일 때 기본값 할당 가능
    • 구조분해 없이 두 변수의 값 교환도 가능
    • 기존에 배열[0], 배열[1] 로 사용하던 것을 이름을 할당하여 사용 가능
    • (내 생각으로는 배열 구조 분해는 사용하면 배열에 있는 원소를 사용하기 위해서 열심히 배열 번호를 안세도 될 거 같아서 좋을 것 같다.)
    • 배열 교환도 쉽게 가능하다.(let 일 때만 가능)
        <script>
          //배열
          const lists = ["apple", "grape"];
          //const로 할당하였을 때 배열 원소는 접근하여 변경할 수 있지만 배열을 바꿀 수 있다.
          //즉, item1 = 'peach' 가능, [item1, item2] = [item2, item1]은 불가능 , let은 가능
          //기존 방식
          console.log(lists[0], lists[1]);
          //구조 분해
          [item1, item2] = lists;
          console.log(item1, item2);
          //교환
          let x = 1,
            y = 3;
          [x, y] = [y, x];
          console.log(x, y);
        </script>

    결과 확인


    객체 분해 구조

    • const {변수} = 객체;
    • 객체 안의 속성을 변수명으로 사용
    • (:)을 이용해 새 변수명을 선언하고, 원래의 값을 새 변수명에 할당할 수 있다.
    • 객체는 key: value 형태로 배열, 함수도 선언이 가능하다.
    • 이렇게 선언된 객체를 순서 상관없이 키 값이 동일하면 value 값을 가져 올 수 있다.
    <script>
          //객체
          const Person = {
            //key: value
            name: "Martin",
            age: 19,
            gender: "M",
            friends: ["Alex", "Kevin"], //배열도 선언 가능
            hello: function () {
              //함수도 선언 가능
              console.log("hello");
            },
            "j-1": "America", // 특수문자는 따옴표안에 있어야 한다.
          };
          console.log(Person.name); // . 으로 접근하는게 가장 기본
          console.log(Person["name"]); //
          console.log(Person["j-1"]); //특수문자로 인해 [""] 사용
          Person.age = 29; //할당 value 변경
          console.log(Person.age);
          console.log(Person.friends[1]);
          Person.hello();
          Person.city = "Seoul";
          console.log(Person);
    
          //예시
          const Persons = [{}, {}, {}]; //배열안에 객체를 선언하여 사용가능.
          const city = "Busan";
    
          //객체구조분해
          const { name, city:newCity, gender, key1 = "Hi" } = Person; //순서 상관없이 가져올 수 있지만 키 값이 똑같아야 한다. , 할당도 가능
          //중복이 되는 경우 city:newCity로 새롭게 정의할 수 있다.
          console.log(name, city, gender, key1, newCity);
          //city는 Busan / newCity는 Seoul
        </script>

    결과 확인


    ...연산자

    spread 연산자

    • 호출하는 함수의 파라미터에 사용
    • 배열을 해체할 때 많이 사용함
    • 기존에는 concat 함수를 사용하여 배열을 해체하여 합침
    • spread를 사용하면 해체하여 배열을 합칠 수 있다.
    <script>
          //spread 연산자 (...) //배열을 해체할 때 많이 사용함.
          const a = [1, 2, 3];
          const b = [4, 5];
          //기존 합치는 법 (concat함수 사용)
          const concat = a.concat(b);
          console.log(concat);
          //spread
          const spread = [...a, ...b];
          const spread1 = [...b, ...a];
          console.log(spread);
          console.log(spread1);
    
          const Person = {
            name: "kang",
            age: 26,
          };
          console.log({ ...Person });
          const c = "Hello";
          console.log([...c]);
        </script>

    결과 확인

    rest 파라미터

    • 호출받는 함수의 파라미터에 사용
    • 호출하는 함수의 파라미터 순서에 맞춰 값 설정 후 남은 파라미터 값을 배열로 설정
    • 나머지 값들을 받아올 때 사용하며 마지막에 있어야 사용이 가능하다.
    <script>
          //rest파라미터 나머지 값들을 받아올 때 사용, 뒤에 있어야 사용이 가능하다.
          function get(a, ...rest) {
            console.log(a);
            console.log(rest);
          }
          get(10, 20, 30, 40, 50);
        </script>

    결과를 보면 뒤에 값들이 배열로 들어간거 확인할 수 있다.

    클래스

    • 객체를 생성하기 위한 템플릿
      • ex). 
      • 객체: 고양이 그 자체
      • 속성: 이름 - 나비 / 나이 - 1살
      • 메소드 : mew() - 울다 / eat() - 먹는다. 
      • class안에서 함수를 선언할 때는 function 키워드 없이 생성한다.
    <script>
          //클래스
          class Cat {
            //생성자
            constructor(name, age) {
              //속성값
              this.name = name;
              this.age = age;
            }
            //메소드
            mew() {
              console.log("야옹");
            }
            eat() {
              console.log("먹이를 먹습니다.");
            }
          }
          const Cat1 = new Cat("나비", 1);
          console.log(Cat1);
          Cat1.mew();
          Cat1.eat();
        </script>

    실행 결과


    자주 사용하는 Javascript 문법을 정리했습니다.

     

    https://github.com/DongHo-Kang/KDT-8-web/tree/458e06cdc6a0637d0995181f0fc9d124974cca3d/230731_destruct

     

    728x90
Designed by Tistory.