본문 바로가기

Javascript/이론+예제

[ES6 문법] 전개 연산자 (spread operator)

 

Do it! 리액트 프로그래밍 정석 책을 보면서 공부한 내용을 정리하는 글입니다.

 


 

전개 연산자란

 

- 나열형 자료를 추출하거나 연결할 때 사용하는 문법

- 배열이나 객체, 변수명 앞에 마침표 세 개(...) 를 입력하는게 특징

- 배열, 객체, 함수 인자 표현식([].{},()) 안에서만 사용해야함

 


 

이전 배열 문법 예제

 

1. 배열의 각 요소를 추출하여 새로운 배열을 만듬

const array1 = ['one', 'two'];
const array2 = ['three', 'four'];

const combined = [array1[0], array1[1], array2[0], array2[1]];
console.log(combined)

 

2. concat () 함수로 두 배열을 합치기

const array1 = ['one', 'two'];
const array2 = ['three', 'four'];

const combined = array1.concat(array2)
console.log(combined)

 

3. 인덱스로 배열 요소를 추출

const array1 = ['one', 'two'];
const array2 = ['three', 'four'];

const combined = [].concat(array1, array2)
console.log(combined)

 

4. || 연산자와 조합해, 추출할 배열 요소가 없을 때 기본 값 지정

const first = array1[0]
const second = array1[1]
const three = array1[2] || "empty"

console.log(three)
=> empty

 

5. 특수 변수 (arguments) 를 사용해 함수 내 인자 항목들을 배열로 변환

function func(a,b,c) {
    const args = Array.prototype.slice.call(arguments)
    const first = args[0]

    console.log(args)
    => [1,2,3]
    console.log(first)
    => 1
}

func(1, 2, 3)

 

6. 인덱스 범위에 해당하는 배열 요소를 추출

function func(a,b,c) {
    const args = Array.prototype.slice.call(arguments)
    const others = args.slice(1, args.length)
    
    console.log(others)
    => [2,3]
}

func(1, 2, 3)

 


 

배열 전개 연산자 예제

 

1. 두 배열 항목을 전개 연산자로 합침

const array1 = ['one', 'two'];
const array2 = ['three', 'four'];

const combined = [...array1, ...array2]

console.log(combined)
=> ['one', 'two', 'three', 'four']

 

2. 배열 각 위치에 있는 요소 추출

const array1 = ['one', 'two'];
const array2 = ['three', 'four'];

const [ first, second ] = array1;

console.log(first, second)
=> one two

 

3. 기본값과 함께 배열 요소 추출

const array1 = ['one', 'two'];

const [ first, second, third = "three" ] = array1;

console.log(third)
=> three

 

4. 추출하고 남은 요소 추출

const array1 = ['one', 'two', 'three', 'four'];

const [ first, second, ...others ] = array1;

console.log(...others)
=> three, four

올바르지 않은 예

const array1 = ['one', 'two', 'three', 'four'];

const wrongArr = ...array1;

console.log(...wrongArr)
=> Error

 

5. 함수 인자 배열을 변수에 할당

function func (...args){
    const [first, ...others] = args;

    console.log(first)
    console.log(...others)
}

func(1,2,3)
=> 1
   2 3

 


 

이전 객체 문법 예제

 

1. 키에 해당하는 값을 추출

const obj1 = { one : 1, two : 2, other : 0 };
const obj2 = { three : 3, four : 4, other : -1 };

const combined = {
    one : obj1.one,
    two : obj1.two,
    three : obj2.three,
    four : obj2.four
}

console.log(combined)
=> {one: 1, two: 2, three: 3, four: 4}

 

2. 객체 내장 함수 assign() 사용하여 두 객체 병합

assign()

- 첫번째 인자는 결과로 반환할 객체 ( {} )
- 나머지 인자는 병합할 객체
- 병합할 객체는 앞에 있는 객체부터 덮어씌움
const obj1 = { one : 1, two : 2, other : 0 };
const obj2 = { three : 3, four : 4, other : -1 };

const combined = Object.assign({}, obj1, obj2)

console.log(combined)
=> {one: 1, two: 2, other: -1, three: 3, four: 4}
중복되는 키 값이 있을 경우 이후에 전달된 객체의 값으로 덮어씌움
( obj1 에 있는 other 값으로 덮어씌워지는 모습 )
const obj1 = { one : 1, two : 2, other : 0 };
const obj2 = { three : 3, four : 4, other : -1 };

const combined = Object.assign({}, obj2, obj1)

console.log(combined)
=> {three: 3, four: 4, other: 0, one: 1, two: 2}

 


 

객체 전개 연산자 예제

 

1. 두 객체를 병합

const obj1 = { one : 1, two : 2, other : 0 };
const obj2 = { three : 3, four : 4, other : -1 };

const combined = {
    ...obj1,
    ...obj2
}

console.log(combined)
=> {one: 1, two: 2, other: -1, three: 3, four: 4}
마지막에 사용한 객체의 값으로 덮어씌워짐 (이전 과 같음)

 

2. 객체에서 특정 값을 추출

const obj1 = { one : 1, two : 2, other : 0 };
const obj2 = { three : 3, four : 4, other : -1 };

const combined = {
    ...obj1,
    ...obj2
}

const { one , ...others } = combined;

console.log(one)
=> 1
console.log(others)
=> {two: 2, other: -1, three: 3, four: 4}
1. 추출할 때는 추출하려는 키 이름 (one , two 등) 으로 맞춰야함.
2. 나머지는 전개 연산자로 선언된 변수 (others) 에 할당 가능

 

'Javascript > 이론+예제' 카테고리의 다른 글

[ES6 문법] 클래스 (Class)  (0) 2023.01.18
[ES6 문법] 가변 변수와 불변 변수  (0) 2023.01.17
[ES6 문법] 템플릿 문자열 (template string)  (0) 2023.01.17
Call , Apply, Bind  (0) 2022.12.30
this  (0) 2022.12.29