๐ด Introduction to Spread
โช spread๋ ๋ณ์๋ฅผ ๊ฐ์ ธ๊ฐ์ ์์๋ฅผ ์ ๊ฐํ๋ค.
const friends = [1, 2, 3, 4];
const family = ["a", "b", "c"];
console.log(friends); // [1, 2, 3, 4] => array
console.log(...friends); // 1 2 3 4 => elements
// spread merge
console.log([friends, family]); // [ [1, 2, 3, 4], ["a", "b", "c"] ]
console.log([...friends, ...family]); // [1, 2, 3, 4, "a", "b", "c"]
๐ Spread Applications
// spread add
const first = ["mon", "tue", "wed"];
const weekend = ["sat", "sun"];
const fullWeek = [...first, "thu", "fri", ...weekend];
console.log(fullWeek);
// conditional spread
const lastName = prompt("Last name");
const user = {
userName: "ryong",
age: 28,
...(lastName !== "" && { lastName })
};
console.log(user); // {userName: "ryong", age: 28, lastName: "lalala"}
๐ก Intro to Rest Parameters
const bestFriendMaker = (firstOne, ...rest) => {
console.log(`My best friend is ${firstOne}`); // ~ ryong
console.log(rest); // ["lin", "hyun", "hun"]
};
bestFriendMaker("ryong", "lin", "hyun", "hun");
๐ข Rest + Spread + Destructure Magic
โช object๋ฅผ ์ง์ฐ๊ฑฐ๋ ์ ๋ฆฌํ ๋ ์ฌ์ฉ
const user = {
name: "ryong",
age: 28,
password: 12345
};
const killPassword = ({ password, ...rest }) => rest;
const cleanUser = killPassword(user);
console.log(cleanUser); // {name: "ryong", age: 28}
โช ๊ธฐ๋ณธ๊ฐ ์ค์ ํ๊ธฐ
const user = {
name: "ryong",
age: 28,
password: 12345
};
const setCountry = ({ country = "KR", ...rest }) => ({ country, ...rest });
console.log(setCountry(user));
// {country: "KR", name: "ryong", age: 28, password: 12345}
โช key ๊ฐ ๋ณ๊ฒฝํ๊ธฐ
const user = {
NAME: "ryong",
age: 28,
password: 12345
};
const rename = ({ NAME: name, ...rest }) => ({ name, ...rest });
console.log(rename(user));
// {name: "ryong", age: 28, password: 12345}
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ JS ] Promises (0) | 2022.07.06 |
---|---|
[ JS ] For Loop (0) | 2022.07.05 |
[ JS ] Destructuring (0) | 2022.07.05 |
[ JS ] Array (0) | 2022.07.05 |
[ JS ] Strings (0) | 2022.07.05 |