비구조화 할당과 spread & rest

Jeon seong jin·2020년 4월 7일
0

JavaScript

목록 보기
9/11

비구조화 할당

여러 라인에 걸쳐 적어야만 했던 할당을 보다 간결하게 쓸 수 있다.
객체 안에 있는 값을 추출해서 변수 혹은 상수로 바로 선언이 가능하다!

보통 객체의 값에 접근할 때

const obj = {a : '나는 1 입니다.', b : '나는 2 입니다.'}
const a1 = obj.a
a1 //'나는 1 입니다.'

객체의 비구조화 할당

/* {}를 이용하여 뺀다.*/
const {a,b} = obj;
a //'나는 1 입니다.'
b // '나는 2 입니다.'

배열도 비구조화 할당이 가능하다!

보통 배열 arrat의 값을 가져오는 방법

const arrat = ['one','two'];
const nomal = arrat[0];
nomal // 'one';

배열의 비구조화 할당

const [oee,tee] = arrat;
oee // 'one';
tee // 'tee';

비구조화 할당을 이용한 다른 예시

const animal = {
  name : '멍멍이',
  type : '개',
}

// const {name} = animal;

// console.log(name);

//이름을 바꿔 주려면???? 

// 원래 이름을 key로 || value는 바꿀 이름 
const {name : nickname} = animal;

//그렇다고 해서 원래 객체의 이름이 변경되는 것은 아니다.
console.log(animal);
const deepObject = {
  state : {
   information : {
      name : 'vel',
    languages : ['ko','en'],
   }
  },
  value : 5
};

const {name,languages} = deepObject.state.information
const {value} = deepObject

name // 'vel'
languages // ['ko','en']
value // 5

나머지 연산자(rest)

비구조화 할당을 사용하되, 배열의 일부 부분 배열을 다른 변수에 할당하고자 할 때 나머지 연산자를 사용한다.
객체 배열 함수의 파라메터에서 사용이 가능하다. 참고로 배열에서 rest는 맨 앞에서 사용할 수 없다!

const [a, ...restArr] = [1,2,3,4,5];
console.log(...restArr) // [2,3,4,5]

//나머지 연산자는 함수 인자에도 사용할 수 있다.
const nomalFunc = (a1,a2,...restNum) => {
  console.log(...restNum) //[3,4]
}
nomalFunc(1,2,3,4)

const purple = {
  name : '슬라임',
  attribute : 'cute',
  color : 'purple'
}

// 객체 비구조화 할당을 하면서 ...rest를 넣어준다.
const {color,...나머지} = purple;
나머지 // {name : '슬라임', attribute : 'cute'}

// atribute를 없애고 싶다면?
const {attribute, ...나머지2} = 나머지
나머지2 // {name : 나머지}

함수 파라미터에서의 rest

  • 함수 파라미터로 rest를 사용하여 유동적으로 사용이 가능하게끔 만든다.
function sum(...rest) {
 return rest.reduce((acc,item) => {
   return acc + item;
 })
}
let result = sum(1,2,3,4,5,6,100);
console.log('result :',result)

전개 연산자(spread)

여러 개의 변수가 들어갈 자리에 한 배열의 원소들을 분포시키고자 할 때 전개 연산자를 사용할 수 있다. 나머지 연산자가 여러 원소를 하나의 배열로 묶어주는 역할 이라면, 전개 연산자는 하나의 배열을 여러 원소들로 풀어주는 역할

function logThings(a,b,c) {
  console.log(a); // 1
  console.log(b); // 2
  console.log(c);//  3
}

const arr = [1,2,3];
logThings(...arr)

// 배열뿐만이 아닌 객체에 대해서도 비슷하게 나머지/전개 연산자를 추가할 수 있는 프러포절이 진행

const {x,y,...z} = {x : 'one' , y : 'two', k : 'three', z : 'f'}

x // one
y // two
z // {k : 'three' , z : 'f'}

const n = {x,y,...z};
console.log(n) // {x : 'one' , y : 'two', k : 'three', z : 'f'}
profile
-기록일지

0개의 댓글