본문 바로가기
웹(web)/프론트엔드-javascript

rest, spread

by 바코94 2020. 6. 28.

const slime = { name: '슬라임', attribute: 'cute', color: 'red'};이 있다고 하자.

name 속성을 비구조화 할당하고 나머지는 others에 저장하려면 어떻게 할까?

const { name, ...other } = slime;

 

slime속성에 추가로 height: 180을 가지는 객체 tall_slime를 만들려면 어떻게 할까?

const tall_slime = { ...slime, height: 180};

 

const numbers = [0,1,2,3,4];이 있다고 하자. 

0,1을 one,two 변수에 담고 나머지는 others에 저장하려면 어떻게 할까?

const [one, two, ...others] = numbers;

 

numbers가 두번 반복하는 [0,1,2,3,4 , 0,1,2,3,4]를 만들려면 어떻게 해야할까?

[...numbers, ...numbers];

 

함수로 몇 개의 인자가 올지 모를 때 어떻게 할까?

function (...rest) {} 

 

숫자를 여러 개 받아서 총합을 구하는 함수를 작성하면?

function sum(...rest) {

return rest.reduce((acc, cur) => acc + cur, 0);

}

const res = sum(1, 2, 3);

 

위 함수에 배열을 사용해 호출하려면?

const numbers = [0, 1, 2, 3, 4];

sum(...numbers);

 

 

 

 

'웹(web) > 프론트엔드-javascript' 카테고리의 다른 글

비동기, Promise  (0) 2020.11.08
scope  (0) 2020.06.29
비구조화 할당(구조분해 할당)  (0) 2020.06.28
falsy 한 값  (0) 2020.06.28
클래스  (0) 2020.06.27