[JS] spread / rest 문법 / 구조 분해 할당

TATA·2023년 1월 3일
0

JavaScript

목록 보기
8/25

✔️ spread 문법

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

sum(...numbers) // 6

배열 합치기가 가능하다.

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];

arr1 = [...arr1, ...arr2];
// arr1 = [0, 1, 2, 3, 4, 5]

새로운 배열에 복사도 가능하다.
(arr2의 배열 값이 바뀐다고 arr의 배열 값이 바뀌진 않는다.)

let arr = [1, 2, 3];

let arr2 = [...arr];
// arr2 = [1, 2, 3];

객체에서도 사용 가능하다.

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
// { foo: 'bar', x: 42 }

let mergedObj = { ...obj1, ...obj2 };
// { foo: 'baz', x: 42, y: 13 }
// 중복되는 게 있다면 뒤에 거로 덮음

함수에서 나머지 파라미터 받아오기도 가능하다.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); // "a" "one"
  console.log("b", b); // "b" "two"
  console.log("manyMoreArgs", manyMoreArgs); // "manyMoreArgs" ["three", "four", "five", "six"]
}

myFun("one", "two", "three", "four", "five", "six");

✔️ rest 문법

reduce

function sum(...numbers) {
  return numbers.reduce((total, current) => {
    return total + current;
  }, 0); // 0은 total의 초기값이 0이라는 뜻이다.
}

sum(1,2,3) // 6
sum(1,2,3,4) // 10

✔️ 구조 분해 할당

분해 후 새 변수에 할당

배열

const [a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

객체

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

{ data : 내가 진짜 원하는 데이터 } = { data : news } 👇

함수에서 객체 분해 예제

function whois({ displayName: displayName, fullName: { firstName: name } }) {
  console.log(displayName + " is " + name);
}

let user = {
  id: 42,
  displayName: "jdoe",
  fullName: {
    firstName: "John",
    lastName: "Doe",
  },
};

whois(user); // jdoe is John
profile
🐾

0개의 댓글