본문 바로가기
모바일 APP/React-Native

전개 연산자

by 살길바라냐 2021. 12. 7.

배열로

const array1 = ['1', '2']
const array2 = ['3', '4']

const combined = [array1[0], array1[1], array2[0], array2[1]];
// 1, 2, 3, 4

const combined = array1.concat(array2);
// 1, 2, 3, 4

const combined = [].concat(array1, array2);
const first = array1[0];
// 1

const second = array1[1];
// 2

const three = array1[2] || 'empty';
// 3 또는 'empty'

function func() {
const args = Array.prototype.slice.call(this, arguments)
// func(a, b, c) -> args[0] = a, args[1] = b, args[2] = c

const first = args[0]
// a

const others = args.slice(1, args.length);
// b, c
}


// 비구조화할당으로 추출하고 남은부분을 전개연산자로 출력
const [first,  second,  three = 'empty', ...others] = array1
// first = '1',  second = '2',  three = 'empty', others = []

func(...args) {const [first, ...others] = args;}
// func(a, b, c) -> args[0] = a, args[1] = b, args[2] = c

 

객체로

 

기존에 사용하던 방법

/ ES5 예제
const objOne = { one: 1, two: 2, other: 0 };
const objTwo = { three: 3, four: 4, other: -1 };

// 내장함수 assign 첫번째 인자는 결과로 반환할 객체이며
// 두번째 인자는 병합할 객체이다.
// 앞에부터 덮어쓰는 특징이있다

const combined = Object.assign({}, objectOne, objectTwo);
// combined = { one: 1, two: 2, three: 3, four: 4, other: -1}
var combined = Object.assign({}, objectOne, objectTwo);
// combined = { one: 1, two: 2, three: 3, four: 4, other: 0}
var others = Object.assign({}, combined);

// 객체를 삭제하는 함수로 other 객체가 삭제된다.
delete others.other;
// combined = { one: 1, two: 2, three: 3, four: 4}

 

전개연산자로 간편하게 사용하는 방법

// ES6 예제
// 키가 중복되면 마지막 사용한 객체값으로 덮어쓴다
var combined = {
  ...objectOne,
  ...objectTwo,
};
// combined = { one: 1, two: 2, three: 3, four: 4, other: -1} 
var combined = {
  ...objectTwo,
  ...objectOne,
};
// combined = { one: 1, two: 2, three: 3, four: 4, other: 0}

// 비구조화 할당으로 other객체만 추출하고 남은 나머지를 출력한다.
var { other, ...others } = combined;
// others = { one: 1, two: 2, three: 3, four: 4}
728x90
반응형