REST AND SPREAD - Introduction to Spread

KimsPractice·2022년 12월 21일
0

ES6의 정석

목록 보기
23/30
post-thumbnail

출처 : Nomadcoders ES6의정석

이번 섹션은 spread 와 rest를 알아볼것이다.
둘 중에 우선 spread에 대해 알아보자.

spread가 무엇이냐면, 배열 혹은 오브젝트와 같이 반복가능한 데이터에 대해 개별요소로 분리하여 배열 혹은 객체에 사용할 수 있다.

예시를 보자.

const numbers = [1,2,3,4];
const alphabets = ["a","b","c","d"];

const combined = number + alphabets
console.log(combined)

우리는 numbers와 alphabets 두개의 배열을 합쳐 하나의 배열로 만들고 싶다고 가정하자.
위처럼 + 를 사용했을때는 우리 원하는 결과가 아닌 두개의 배열이 합쳐진 문자열을 보게될 것이다.

우리가 원하는 형태의 데이터를 만들기 위해서 우리는 기존에 배열에 관한 메서드들을 사용해 분해하고 다시 배열을 만들고 배열안에 데이터를 넣고 많은 작업을 해줬어야 했다.

그렇지만 spread operator를 활용하면 간단하게 처리할 수 있게 된다.
spread operator은 ...을 붙여 사용한다.

const numbers = [1,2,3,4];
const alphabets = ["a","b","c","d"];

const combined = [...numbers, ...alphabets]
console.log(combined)


spread operator를 사용하면 이처럼 간단하게 배열들을 하나로 합칠 수가 있다.
다른 유형을 하나 더 보자면, 배열 중간에 데이터가 들어가야되는 경우에는 어떻게 처리해야할까

이 또한 spread operator를 활용하면 간단하게 처리할 수 있다.

const alphabets = ["a","b","c","d"];

const combined = ["가","나",...alphabets,"다","라"]
console.log(combined)

물론 객체에서도 같은 방식으로 사용할 수 있다.

const numbers = {
  1:"1",
  2:"2",
  3:"3",
  4:"4"
}

const alphabets = {
  a : "a",
  b : "b",
  c : "c",
  d : "d"
}

const combined = {...numbers,...alphabets}

console.log(combined)

const alphabets = {
  a : "a",
  b : "b",
}

const combined = {: "가",
  ...alphabets,: "나", 
}

console.log(combined)

profile
난 그냥 살아 아주잘살아

0개의 댓글