WEB/JavsScript

[JavaScript] Spread & Destructuring

Raymond 2022. 5. 24. 21:52

spread operator


<script>
  // 배열을 합치려면 concat()을 사용해야한다. 하지만 spread operator을 사용하면 편리하다.
  let arr1 = [1, 2, 3];
  let arr2 = [4, 5, 6];
  let arr3 = arr1.concat(arr2);

  // spread operator
  // 배열을 분해해서 각각의 요소를 다 따로 분리해준다.
  let arr4 = [...arr1, ...arr2];
  console.log(arr4);

  let strArr1 = ["A", "B", "C"];
  let strArr2 = ["D", "E", "F"];
  let strArr3 = [...strArr1, ...strArr2];
  console.log(strArr3);
</script>

 

참고자료

https://ko.javascript.info/rest-parameters-spread

 

array_destructuring


let [firstName, surname] = getName();

분해와 동시에 firstName과 surname의 변수에 값을 할당한다.

<script>
  // 이름과 성을 요소로 가진 함수
  function getName() {
    return ["Bora", "Lee"];
  }

  // 일반적인 방법
  let full = getName();
  let first = full[0]; // Bora
  let second = full[1]; // Lee

  // array destructuring 이용
  let [firstName, surname] = getName();
  console.log(firstName); // Bora
  console.log(surname); // Lee
</script>

 

object_destructuring


let { firstName, lastName } = getPerson();

분해와 동시에 firstName과 lastName의 변수에 값을 할당한다.

<script>
  // 고객 정보를 가져오는 함수
  function getPerson() {
    return {
      firstName: "John",
      lastName: "Doe",
      age: 37
    };
  }

  let person = getPerson();
  console.log(person.firstName);
  console.log(person.lastName);

  // 오브젝트의 키-값 쌍이 많지만, 내가 필요한 건 이중에 몇개만 필요할때
  // 코드 작성의 효율성 + 가독성 증가
  let { firstName, lastName } = getPerson();
  console.log(firstName);
  console.log(lastName);
</script>

 

참고자료

https://ko.javascript.info/destructuring-assignment