TIL_ES6

박성훈·2022년 7월 12일
0

JavaScript

목록 보기
13/25
post-thumbnail

spread / rest

spread

배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소를 넣을 때 사용

function sum(x, y, z){
	return x + y + z;
}

const numbers = [1,2,3];

sum(...numbers);

...numbers는 배열 [1,2,3]을 풀어서 각 요소들을 할당해준다.

rest

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

function sum(...theArgs){
	return theArgs.reduce((previous, current) => {
    	return previous + current;
    });
}

파라미터의 개수가 가변적일 경우, 파라미터를 배열의 형태로 받아서 사용할 수 있다.

활용

배열합치기

let parts = ['sholders', 'knees'];

let lyrics = ['head', ...parts, 'and];

console.log(lyrics) // ['head', 'sholders', 'knees', 'and']

newArr = lyrics.concat(parts) // 동일한 결과

배열 복사

let arr = [1,2,3]
let arr2 = [...arr]; // 객체는 참조 자료형 -> 새로운 주소값을 가진 객체가 생성

arr2.push(5); // immutable하기 때문에 arr은 수정되지 않는다.

arr2.slice() // 동일한 결과

객체

let obj = {
	name : 'kim',
    age : 24
}

let obj2 = {
	age : 27,
    job : 'developer'
}

let mergeObj = {...obj, ...obj2} 

위의 코드의 결과는

mergeObj = {
	name : 'kim',
    age : 27,
    job : 'developer'
}

객체와 객체가 합쳐질 경우 공통된 키값에 대해서는 나중에 합쳐진 객체의 value값을 적용한다.

파라미터

function func(a, b, ...args){
	console.log(a);
	console.log(b);
	console.log(...args);
}

func('one', 'two', 'three', 'four', 'five');

위의 코드의 결과는

one //a
two //b
['three', 'four', 'five'] //args

뒤의 나머지 값을 배열의 형태로 할당하게 된다.
이때, 파라미터의 마지막부분에 spread 파라미터를 넣어줘야한다.

구조분해할당

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)

whois함수에서
displayName: displayName -> displayName변수에 user객체의 displayName키의 value값을 할당한다.
fullName: {firstName: name} -> name변수에 user객체의 fullName키안의 firstName키의 value값을 할당한다.

이런 방식으로 객체를 쪼개서 함수의 파라미터로 받을 수 있다.

profile
프론트엔드 학습일지

0개의 댓글