[자바스크립트] - ... spread, rest

큘피·2024년 6월 18일

JavaScript-codingtest

목록 보기
4/6

Spread 연산자

Spread 연산자는 배열이나 객체를 개별 요소로 분리하는 데 사용됩니다. 이를 통해 배열이나 객체의 요소를 쉽게 복사하거나 합칠 수 있습니다.

배열에서의 Spread 연산자

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

const arr3 = [4, 5];
const arr4 = [...arr1, ...arr3]; // [1, 2, 3, 4, 5]

객체에서의 Spread 연산자

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

const obj3 = { b: 4, d: 5 };
const obj4 = { ...obj1, ...obj3 }; // { a: 1, b: 4, d: 5 }

함수 호출에서의 Spread 연산자

function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

Rest 연산자

함수의 인자나 배열 또는 객체에서 나머지 요소를 하나의 변수로 수집하는 데 사용됩니다. Rest 연산자는 주로 함수의 매개변수에서 사용되며, 남은 모든 인자를 배열로 모을 수 있습니다.

함수 매개변수에서의 Rest 연산자

function sum(...args) {
  return args.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

배열 비구조화 할당에서의 Rest 연산자

const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest);  // [2, 3, 4]

cf) const [...rest, last]  이런건 불가능

객체 비구조화 할당에서의 Rest 연산자

const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(a);    // 1
console.log(rest); // { b: 2, c: 3 }
profile
취준생의 개발블로그

0개의 댓글