ES6 주요 문법

moono·2023년 1월 3일
0

JavaScript

목록 보기
12/23

spread/rest 문법

spread 문법

  • 배열을 풀어서 인자로 전달하거나, 각각의 요소로 넣을 때 사용
  • 선물 개봉할 때 포장지를 흩뿌리듯이(spread) 배열[] 에서 벗어난다
function sum(x, y, z) {
  return x + y + z;
}
const number = [1, 2, 3];
sum(...number) // 6 ⇒ 1 + 2 + 3 을 한 것
  • 배열에서 사용할 때 강력한 힘을 발휘한다.

rest 문법

파라미터를 배열의 형태로 받아서 사용 ⇒ 파라미터 개수가 가변적일 때 유용

  • 쓰고 남은 나머지(rest) 매개변수 를 불러와서 배열의 형태로 사용
function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current; // 지금까지 계산 된 값 + 현재 값
  }); // 초기값 `,0` 을 넣어도 되는데 옵션이라 안 넣으면 0으로 시작함
}

sum(1,2,3) // 6 ⇒ 0+1=1, 1+2=3, 3+3=6
sum(1,2,3,4) // 10 ⇒ 0+1=1, 1+2=3, 3+3=6, 6+4=10

.reduce 는 함수를 받는데 이전 값(previous) 과 현재 값(current)
이전 값은 누적된 계산값 이라고 생각해야 함



활용하기

배열 합치기

  • spread 문법은 기존 배열을 변경하지 않으므로(immutable), 값을 바꾸려면 새롭게 할당해야 함
let parts = ['shoulders'. 'knees']
let lyrics = ['head', ...parts, 'and', 'toes'];

console.log(lyrics) // ['head', 'shoulders', 'knees', 'and', 'toes']
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // [0, 1, 2, 3, 4, 5]

배열 복사

  • spread 문법은 기존 배열을 변경하지 않으므로(immutable), arr2를 수정한다고 기존 배열이 바뀌지 않음
let arr1 = [0, 1, 2];
let arr2 = [...arr1]; // arr1.slice() 와 유사
arr2.push(4); // 4

console.log(arr2) // [0, 1, 2, 4]
console.log(arr1) // [0, 1, 2]

객체에서 사용하기

let obj1 = {foo: 'bar', x: 42}
let obj2 = {foo: 'bax', y: 13}

let clonedObj = {...obj1};
let mergedObj = {...obj1, ...obj2};

console.log(clonedObj); // {foo: 'bar', x: 42}
console.log(mergedObj); // {foo: 'bax', x: 42, y: 13}

함수에서 나머지 파라미터 받아오기

function myFun(a, b, ...manyMoreArgs) {
  console.log('a', a);
  console.log('b', b);
  console.log('manyMoreArgs', manyMoreArgs);
}

myFun('one', 'two', 'three', 'four', 'five');
// 콘솔 순서
// a one
// b two
// manyMoreArgs ['three', 'four', 'five']

분해 후 새 변수에 할당

  • 배열
const [a, b, ...rest] = [1, 2, 3, 4, 5];

console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

  • 객체
const {c, d, ...rest} = {a: 1, b: 2, c: 3, d: 4, e: 5};

console.log(c) // 3
console.log(d) // 4
console.log(rest) // {a: 1, b: 2, e: 5} 

함수에서 객체 분해

function whois({displayName: displayName, fullName: {firstName: name}}) {
  console.log(displayName + ' is ' + name);
}

let user = {
  id: 42,
  displayName: 'jdoe',
  fullName: {
    firstName: 'John',
    lastName: 'Doe'
  }
};

whois(user) // jdoe is John

0개의 댓글