비구조화 할당, spread/rest

gogori6565·2022년 7월 7일
0

JavaScript

목록 보기
6/10

비구조화 할당 (Destructuring)

const me = {
  name: "홍길동",
  age: 19,
};

const name = me.name;
const { name } = me;
//name에 홍길동 할당되는 같은 코드
const name = me.name;
const age = me.age;

const { name, age } = me;
//name, age가 me의 내용으로 할당되는 같은 코드

배열의 0번째 요소를 비구조화

const a = arr[0];
const [a] = arr;
//배열의 0번째 요소 a에 할당

배열의 여러 요소를 비구조화

const a = arr[0];
const b = arr[1];

const [a,b] = arr;
//배열의 0,1번째 요소 각각 a,b에 할당

스프레드 (Spread)

: 내용물 흩뿌리기

const me = {
  name = "홍길동",
  age = "19",
}

const marryme = {
  name = "홍길동",
  age = "19",
  marry = false,
}

name과 age가 중복되므로,

const marryme = {
  me,
  marry = false,
}

me, 는 me라는 객체가 따로 또 들어간 걸로 해석됨
즉, 출력시
me: {name: "홍길동", age: 19}
marryme: false

const marryme = {
  ...me,
  marry = false,
}

...me me 앞에 ...을 붙여주면 <= spread 사용
name: "홍길동"
age: 19
marryme: false
정상 출력됨


배열 예시

const animals = {"개", "고양이"}
const anotherAnimals = {...animals, "소"}

=> anotherAnimals에 개, 고양이, 소 할당됨


rest(나머지)

: spread와 반대 기능, 내용물 합치기

const me = {
  name = "홍길동",
  age = "19",
  marry = false,
}

const { marry, ...another } = me;

이 경우, marry를 제외한 name과 age를 담은 'another'이라는 객체가 생성됨

배열도 마찬가지

const numbers = {0,1,2,3,4,5};

const {zero, ...rest} = numbers;

이 경우, zero를 제외한 나머지 1,2,3,4,5 element를 담은 'rest'라는 객체가 생성됨

profile
p(´∇`)q

0개의 댓글