[React] Operator

차슈·2024년 5월 17일
0

REACT

목록 보기
6/12
post-thumbnail

1. Spread Operator

1-1. 객체에서의 사용

객체의 속성을 쉽게 다른 객체로 복사하거나 확장할 때 사용

const originalUser = { name: "홍길동", age: 20 };
const updatedUser = { ...originalUser, location: "한국" };
console.log(updatedUser);  
// { name: "홍길동", age: 28, location: "한국" }

1-2. 배열에서의 사용

두 배열을 합칠때 사용

const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = [...first, ...second];
console.log(combined);  
// [1, 2, 3, 4, 5, 6]

예제

두 배열을 합친 새 배열을 만들기

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

정답

const combinedArray = [...array1, ...array2];
console.log(combinedArray); // [1, 2, 3, 4, 5, 6]

const clonedArray = [...array1];
array1.push(4);
console.log(clonedArray); // [1, 2, 3]
console.log(array1);      // [1, 2, 3, 4]

2. Rest Operator (나머지 연산자)

함수의 매개변수 에서 사용되거나 객체/배열 리터럴에서 남음 부분을 하나의 변수로 그룹화할때 사용
즉, 특정 속성을 제외한 나머지 속성들을 새 객체로 그룹화할때 사용

2-1. 함수 매개변수

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

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

2-2. 객체 분해 할당

const person = {
    name: "John",
    age: 30,
    country: "USA",
    occupation: "Developer"
};

const { country, ...rest } = person;
console.log(rest);
// { name: "John", age: 30, occupation: "Developer" }

0개의 댓글