2023. 2. 9. 20:01ㆍ개인노트-인강
# 6.0 Introduction to Spread
Spread 구문
Spread 구문을 사용하면 배열, 문자열, 객체 등 반복 가능한 객체 (Iterable Object)를 개별 요소로 분리할 수 있습니다.
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // arr1 은 이제 [0, 1, 2, 3, 4, 5]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
# 6.1 Spread Applications
무언가를 추가하기, 합치기, 업데이트 하기!
## Array
const friends = ["nico", "lynn"];
const newFriends = [...friends, "dal"];
// 앞에다 추가하고 싶다면?
// const newFriends = ["dal", ...friends];
console.log(newFriends);
## Object
const nico = {
username= "nico",
};
console.log({ ...nico, password: 123 });
## 활용
const first = ["mon", "tue", "wed"];
const weekend = ["sat", "sun"];
const fullweek = [...first, "thu", "fri", ...weekend];
console.log(fullweek);
## 조건부 object
속성을 조건부로 추가하기.(optional object property)
예시용 객체.
const user = {
username: "nico",
age: 24,
};
위 코드에 lastName의 값을 조건부로 추가하려면..
const lastName = prompt("Last name : ");
const user = {
username: "nico",
age: 24,
lastName: lastName !== "" ? lastName : undefined,
};
console.log(user);
// 출력
// lastName에 무언가를 입력했을 경우 : 입력한 내용 출력
// lastName에 아무것도 입력하지 않았을 경우 : undefined 출력
lastName 속성 자체(key)를 조건부로 추가하려면..
이 경우에 spread가 매우 유용하게 쓰일 수 있습니다.
const lastName = prompt("Last name : ");
const user = {
username: "nico",
age: 24,
...(lastName !== "" && { lastName }),
// lastName: lastName !== "" ? lastName : undefined,
};
console.log(user);
// 출력
// lastName에 무언가를 입력했을 경우 : 해당 객체에 lastName속성 및 할당 값 생성
// lastName에 아무것도 입력하지 않았을 경우 : 해당 객체에 lastName 속성 생성하지 않음.
이 때, lastName을 {}로 감싸주어야 하는 것에 주의해야합니다. (spread로 전개하려면 데이터가 object이어야 하므로)
# 6.2 Intro to Rest Parameters
## rest parameters
이를 가장 잘 설명할 방법은 끝도없는 parameter를 전달받는 함수를 만들어 보는 것입니다.(infinity parameters)
const infiniteArgs = (...kimchi) => console.log(kimchi);
infiniteArgs("1", 2, true, "lalala", [1, 2, 3, 4]);
// 출력
// ["1", 2, true, "lalala", Array(4)]
이것이 rest 구문입니다.
rest는 모든 값을 하나의 변수로 축소(contract)시켜줍니다.
값들의 list를 취한다음에 하나의 변수 안에 넣어버립니다.
rest 구문을 아래처럼 유용하게 활용할 수 있습니다.
const bestFriendMaker = (firstOne, ...rest) => {
console.log(`My best friend is ${firstOne}`);
console.log(rest);
};
bestFriendMaker("nico", "lynn", "dall", "japan guy");
// 출력
// My best friend is nico
// ["lynn", "dall", "japan guy"]
## 정리
- Spread : (변수를) 확장
- Rest : (변수를) 축소
둘 다 변수 앞에 ... 를 붙이며,
parameter 부분에 들어가게 되면 rest라고 부름.
* Rest는 Array 를 만든다.
# 6.3 Rest + Spread + Destructure Magic
## rest의 훌륭한 예시 1. 특정 속성값을 제외시키기
Destructuring을 rest operator하고 함께 사용.
const user = {
name: "nico",
age: 24,
password: 12345,
};
// user["password"] = null;
// console.log(user); // password 값을 null로 변경.
const killPassword = ({ password, ...rest }) => rest;
const cleanUser = killPassword(user);
console.log(cleanUser); // password 속성 자체를 제거.
// 출력
// {name: "nico", age: 24}
// object로 리턴됐다는 점에 유의
이렇게 object를 정리할 때 사용할 수 있습니다.
## rest의 훌륭한 예시 2. 기본값 설정하기
Destructuring을 rest operator하고 함께 사용.
const user = {
name: "nico",
age: 24,
password: 12345,
};
const setCountry = ({country = "KR", ...rest}) => ({ country, ...rest });
console.log(setCountry(user));
// 출력
// { country: "KR", name: "nico", age: 24, password: 12345 }
## rest의 훌륭한 예시 3. 속성명 바꾸기(rename property)
Destructuring을 rest operator하고 함께 사용.
const user = {
NAME: "nico",
age: 24,
password: 12345,
};
const rename = ({ NAME: name, ...rest }) => ({name, ...rest})
console.log(rename(user));
// 출력
// { name: "nico", age: 24, password: 12345 }
'개인노트-인강' 카테고리의 다른 글
| 개인노트 nomad ES6의 정석 #8 Promises (0) | 2023.02.15 |
|---|---|
| 개인노트 nomad ES6의 정석 #7 For of Loop (0) | 2023.02.10 |
| 개인노트 nomad ES6의 정석 #5 Destructuring (0) | 2023.02.06 |
| 개인노트 nomad ES6의 정석 #4 Array (0) | 2023.02.03 |
| 개인노트 nomad ES6의 정석 #3 Strings (0) | 2023.02.02 |