๐ง๐ป๐ป ๊ฐ๋ฐ๊ฐ๋ฐ/javascript
Spread/Rest ๋ฌธ๋ฒ, ๊ตฌ์กฐ๋ถํด
Seungjae Lee
2021. 5. 31. 09:15
Spread ๋ฌธ๋ฒ
์ฃผ๋ก ๋ฐฐ์ด์ ํ์ด์ ์ธ์๋ก ์ ๋ฌํ๊ฑฐ๋, ๋ฐฐ์ด์ ํ์ด์ ๊ฐ๊ฐ์ ์์๋ก ๋ฃ์ ๋์ ์ฌ์ฉํฉ๋๋ค.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers)
// ์ง๋ฌธ: ์ด๋ค ๊ฐ์ ๋ฆฌํดํ๋์? 6
Rest ๋ฌธ๋ฒ
ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐฐ์ด์ ํํ๋ก ๋ฐ์์ ์ฌ์ฉํ ์ ์์ต๋๋ค. ํ๋ผ๋ฏธํฐ ๊ฐ์๊ฐ ๊ฐ๋ณ์ ์ผ ๋ ์ ์ฉํฉ๋๋ค.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
sum(1,2,3)
// ์ง๋ฌธ: ์ด๋ค ๊ฐ์ ๋ฆฌํดํ๋์? 6
sum(1,2,3,4)
// ์ง๋ฌธ: ์ด๋ค ๊ฐ์ ๋ฆฌํดํ๋์? 10
๋ฐฐ์ด์์ ์ฌ์ฉํ๊ธฐ
Spread ๋ฌธ๋ฒ์ ๋ฐฐ์ด์์ ๊ฐ๋ ฅํ ํ์ ๋ฐํํฉ๋๋ค.
1. ๋ฐฐ์ด ํฉ์น๊ธฐ
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
// ์ง๋ฌธ: lyrics์ ๊ฐ์ ๋ฌด์์ธ๊ฐ์? ["head", "shoulders", "knees", "and", "toes"]
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
// ์ฐธ๊ณ : spread ๋ฌธ๋ฒ์ ๊ธฐ์กด ๋ฐฐ์ด์ ๋ณ๊ฒฝํ์ง ์์ผ๋ฏ๋ก(immutable),arr1์ ๊ฐ์ ๋ฐ๊พธ๋ ค๋ฉด ์๋กญ๊ฒ ํ ๋นํด์ผ ํฉ๋๋ค.
// ์ง๋ฌธ: arr1์ ๊ฐ์ ๋ฌด์์ธ๊ฐ์? [0, 1, 2, 3, 4, 5]
2. ๋ฐฐ์ด ๋ณต์ฌ
let arr = [1, 2, 3];
let arr2 = [...arr]; // arr.slice() ์ ์ ์ฌ
arr2.push(4);
// ์ฐธ๊ณ : spread ๋ฌธ๋ฒ์ ๊ธฐ์กด ๋ฐฐ์ด์ ๋ณ๊ฒฝํ์ง ์์ผ๋ฏ๋ก(immutable), arr2๋ฅผ ์์ ํ๋ค๊ณ , arr์ด ๋ฐ๋์ง ์์ต๋๋ค.
// ์ง๋ฌธ: arr์ arr2์ ๊ฐ์ ๊ฐ๊ฐ ๋ฌด์์ธ๊ฐ์?
//arr์ ์ํฅ์ ๋ฐ์ง ์๊ธฐ ๋๋ฌธ์ ๊ทธ๋๋ก [1, 2, 3]์ด๊ณ
//arr2 ์ [1, 2, 3, 4] ์ด ๋จ
๊ฐ์ฒด์์ ์ฌ์ฉํ๊ธฐ
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
// ์ง๋ฌธ: clonedObj์ mergedObj์ ๊ฐ์ ๊ฐ๊ฐ ๋ฌด์์ธ๊ฐ์?
//clonedObj
//{foo: "bar", x: 42}
//mergedObj
//{foo: "baz", 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", "six");
// ์ง๋ฌธ: ์ฝ์์ ์์๋๋ก ์ด๋ป๊ฒ ์ฐํ๊น์?
// a one
// b two
// manyMoreArgs ["three", "four", "five", "six"]
๊ตฌ์กฐ ๋ถํด (Destructing)
๊ตฌ์กฐ ๋ถํด ํ ๋น์ Spread ๋ฌธ๋ฒ์ ์ด์ฉํ์ฌ ๊ฐ์ ํด์ฒดํ ํ, ๊ฐ๋ณ ๊ฐ์ ๋ณ์์ ์๋ก ํ ๋นํ๋ ๊ณผ์ ์ ๋งํฉ๋๋ค.
๋ถํด ํ ์ ๋ณ์์ ํ ๋น
๋ฐฐ์ด
const [a, b, ...rest] = [10, 20, 30, 40, 50];
// ์ง๋ฌธ: a, b, rest๋ ๊ฐ๊ฐ ์ด๋ค ๊ฐ์ธ๊ฐ์?
//rest
//[30, 40, 50]
๊ฐ์ฒด
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// ์ง๋ฌธ: a, b, rest๋ ๊ฐ๊ฐ ์ด๋ค ๊ฐ์ธ๊ฐ์?
//rest
//{c: 30, d: 40}
- ๊ฐ์ฒด์์ ๊ตฌ์กฐ ๋ถํด ํ ๋น์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ, ์ ์ธ(const, let, var)๊ณผ ํจ๊ป ์ฌ์ฉํ์ง ์์ผ๋ฉด ์๋ฌ๊ฐ ๋ฐ์ํ ์ ์์ต๋๋ค.
- ์ ์ธ์์ด ํ ๋นํ๋ ๊ฒฝ์ฐ, ์ด ์ฝํ ์ธ ์ ํ๋จ์๋ ๊ณต์๋ฌธ์ ๋งํฌ๋ฅผ ํตํด ๋ด์ฉ์ ํ์ธํ ์ ์์ต๋๋ค.
์ ์ฉํ ์์ : ํจ์์์ ๊ฐ์ฒด ๋ถํด
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