전개 연산자(Spread Operator)

김동환·2023년 8월 14일

Learn_JavaScript

목록 보기
2/10
post-thumbnail

전개 연산자(Spread Operator)란?

  • 전개 연산자(Spread Operator)는 배열이나 객체를 다른 배열이나 객체에 추가할 때 사용하는 연산자이다. 배열을 전개하려면 배열 앞에 ... 기호를 붙인다. 예를 들어, 다음과 같이 배열을 전개할 수 있다.

    const fruits = ['apple', 'banana', 'orange'];
    const newFruits = ['grapes', ...fruits];
    
    console.log(fruits) // ['apple', 'banana', 'orange']
    console.log(newFruits) // ['grapes', 'apple', 'banana', 'orange']
    • 전개 연산자의 위치에 따라 배열 순서가 정해진다.
  • 순서를 바꿔 배열을 전개할 수도 있다.

    const numbers = [1, 2, 3];
    const newNumbers = [...numbers, 4, 5, 6];
    
    console.log(numbers) // [1, 2, 3]
    console.log(newNumbers) // [1, 2, 3, 4, 5, 6]
    • 코드는 다음과 같이 동작한다.
      1. newNumbers라는 새로운 배열을 생성
      2. numbers 배열의 모든 요소를 newNumbers 배열에 추가
      3. newNumbers 배열에 456을 추가

전개 연산자 (Spread Operator) 는 크게 3가지로 나눌 수 있다.

  1. 배열 전개 연산자
  2. 객체 전개 연산자
  3. 문자열 전개 연산자
// 1. 배열 전개 연산자
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5, 6];

// 2. 객체 전개 연산자
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};
const newPerson = { ...person, job: 'Software Engineer' };

// 3. 문자열 전개 연산자
const sentence = 'Hello, world!';
const newSentence = `${sentence} I am a JavaScript developer!`;
profile
프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2023년 8월 14일

훌륭한 글 감사드립니다.

답글 달기