17. Spread 구조부내할당!

홍인열·2021년 9월 9일
1

Spread/Rest 문법

Spread

주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을때 사용한다.
배열앞에 ...Array형태로 사용한다.
기본배열을 변경하지않는다! Immutable

  • spread를 이용하면 아래와 같이 간단히 배열을 합칠 수 있다.
const animals = ['tiger', 'pig', 'dog']
console.log(animals)
// => tiger pig dog
const being = ['tree', 'butterfly', ...animals, 'bird']
console.log(being);
// => ['tree', 'butterfly', 'tiger', 'pig', 'dog', 'bird']
const fruits = ['apple', 'mango', 'melon']
const fusion =[...animals, ...fruits]
console.log(fusion)
// => ['tiger', 'pig', 'dog', 'apple', 'mango', 'melon']
  • 배열의 복사도 손쉽게 가능하다.
const fruits = ['apple', 'mango', 'melon']
const fruits2 = [...fruits] // fruits.slice() 와 유사
console.log(fruits2)
// => ['apple', 'mango', 'melon']
  • 객체도 복사하거나 합칠 수 있다. 사용하고자하는 참조형 타입에 다라 괄호종류를 알맞게 사용해주어야한다.
const animals1 = {name: 'cat', size: 'small'}
const animals2 = {name: 'cow', color: 'brown'}
const clonedAnimal = {...animals1}
console.log(clonedAnimal)
// => {name: 'cat', size: 'small'}
const mergedAnimal = {...animals1, ...animals2}
console.log(mergedAnimal)
// => {name: 'cow', size: 'small', color: 'brown'}
// 동일한 key를 가지고 있을때는 뒤에오는 객체의 속성으로 덮어쓰여진다.

Rest 문법

함수의 마지막 파라미터의 앞에 ... 를 붙여 사용한다. 모든 나머지 인수를 "표준" 자바스크립트 배열로 대체하며, 마지막 파라미터만 "Rest 파라미터" 가 될 수 있다. 즉, 파라미터를 배열의 형태로 받아서 사용할 수 있습니다.

function animals(a, b, ...rest) {
  console.log("first", a);
  console.log("last", b);
  console.log("other", rest);
  return [a,b,rest]
}
// 지정된 매개변수 a, b를 제외한 추가 인수들을 하나의 배열형태로 받는다.
const myAnimals = animals('tiger', 'pig', 'dog', 'apple', 'mango', 'melon');
// => first tiger, last pig, other (4) ['dog', 'apple', 'mango', 'melon']
// myAnimals = ['tiger', 'pig', ['dog', 'apple', 'mango', 'melon']]
function allAnimals(...rest) { //파라미터가 하나면 마지막이기도하다.
  return rest //배열을 반환하게된다.
}
const tooAnimals = allAnimals('tiger', 'pig', 'dog', 'apple', 'mango', 'melon');
// => tooAnimals = ['tiger', 'pig', 'dog', 'apple', 'mango', 'melon']

구조분해

말그대로 배열이나, 객체를 분해해서 손쉽게 변수에 할당 하는 것이다. 변수를 선언하는 것이기때문에 const, let, var같은 선언과 함께 사용해야한다.

  • 배열에서
const [a, b, ...rest] = [10, 20, 30, 40, 50];
//등호 왼쪽 배열과 오른쪽 배열이 있을때, 오른쪽 배열의 값이 동일한 인덱스 값을가진 왼쪽의 요소에 할당되고, 왼쪽의 요소는 변수가 된다! 
console.log(a)
// => 10
console.log(rest)
// => [30, 40, 50]
  • 객체에서
const {a, c, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// 객체의 key를 변수로서 속성을 할당상태로 독립적인 변수로 구조분해가 가능하다.
console.log(a)
// => 10
console.log(rest)
// => {b:20, d:40}
// key값을 그대로 사용하지않고 변수 이름을 변경도 가능하다.
const {a:a2, c:c2, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a2)
// => 10
//이런 경우도 있다. 꺼내고 싶은 속성이, 속성이 개체안에 있을때
const {a:a2, c:c2, ...rest} = {a: 10, b: 20, x:{c: 30, d: 40}}
//key가 'x'인 속성의 객체 내부에 있는 key가 'c'인 속성을 'c2'로 할당했다.
console.log(c2)
// => undefiend, 내부객체에 접근이 불가능하여 할당이 되지않았다. 
// 객체내부의 속성을 할당하는 방법은 다음과 같다.
const {a:a2, x:{c:c2}, ...rest} = {a: 10, b: 20, x:{c: 30, d: 40}}
console.log(c2)
// => 30, 정상적으로 내부객체에 있는 'c'의 속성이 'c2'에 할당 되었다.
profile
함께 일하고싶은 개발자

0개의 댓글