Medium - 8 ways to use the Spread operator in JavaScript.
in Trend
Trend ํ์ ์ ์ํ Medium ๊ธฐ๊ณ ๋ฌธ ํฌ์คํ - ์๋ฐ์คํฌ๋ฆฝํธ์์ ์คํ๋ ๋ ์ฐ์ฐ์๋ฅผ ์ฐ๋ 8๊ฐ์ง ๋ฐฉ์; ์๋ฐ์คํฌ๋ฆฝํธ์์ ์คํ๋ ๋ ์ฐ์ฐ์๋ฅผ ์ฐ๋ ๋ฒ์ ์์๋ด ์๋ค.
Spread Syntax Example
(...)
์คํ๋ ๋ ์ฐ์ฐ์๋ ES6์์ ์ฒ์ ์๊ฐ๋์์ต๋๋ค.
์คํ๋ ๋ ์ฐ์ฐ์๋ ์ํํ ์ ์๋ ๊ฐ์ฒด์ ๊ฐ๋ณ ์์๋ค์ ํ์ฅํฉ๋๋ค. ์ํ ๊ฐ๋ฅํ ๊ฐ์ฒด๋ for of
๋ฃจํ์์ ๋์๊ฐ๋ ๋ชจ๋ ๊ฒ๋ค์
๋๋ค. ์๋ฅผ๋ค๋ฉด ๋ฐฐ์ด, ๋ฌธ์์ด, Map, Set, DOM ๋
ธ๋ ๋ค์ด ์์ฃ .
1.Using Spread Operator in logging
์ํ๊ฐ๋ฅํ ๊ฐ์ฒด๋ฅผ ์ฝ์๋ก๊ทธ ์์์ ์คํ๋ ๋ ์ฐ์ฐ์๋ก ๋ฟ๋ ค์ค ์ ์์ต๋๋ค.
let fruits = ['๐', '๐', '๐', '๐'];
console.log(...fruits); //๐ ๐ ๐ ๐
2.Spread operator for Copying Arrays
let fruits = ['๐', '๐', '๐', '๐'];
let fruitsCopy = [ ...fruits ];
console.log(...fruitsCopy); //๐ ๐ ๐ ๐
๊ฐ์ฒด ๋ณต์ฌ
let user = {name : "John", age: 20 }
let userCopy = {...user}
์คํ๋ ๋ ์ฐ์ฐ์๋ ๋ฅ์นดํผ๊ฐ ์๋๋๋ค. (์ฐธ์กฐํํ)
3.Spread operator for Merging
let fruits = ['๐', '๐', '๐', '๐'];
let vegetables = ['๐
', '๐', '๐ฅ'];
let fruitsAndVeg = [...fruits, ...vegetables];
๊ฐ์ฒด๋ฅผ ๋จธ์งํ ๋ ํค๊ฐ ์ด๋ฏธ ์กด์ฌํ๋ ๊ฒฝ์ฐ ๊ฐ์ฅ ๋ง์ง๋ง ๊ฐ์ฒด์ ํค๋ก ๋ฐ์ดํฐ๊ฐ ๋ฎ์ด์์์ง๋๋ค.
let user1 = { name: "John", age: 20 };
let user2 = { name: "Ram", salary: '20K' };
let userCopy = {...user1, ...user2};
userCopy; // {name: "Ram", age: 20, salary: '20K' };
4.Spread operator for Passing as arguments
function sum(a, b) {
return a+b;
}
let num = [1,2];
sum(...num); // 3
math ํจ์์์๋ ์ฌ์ฉํ ์ ์์ต๋๋ค.
let num = [5,9,3,5,7];
Math.min(...num);
Math.max(...num);
5.Spread operator In Destructuring variable
let [melon, ...fruits ] = ['๐', '๐', '๐', '๐'];
melon; //๐
fruits; // [ '๐', '๐', '๐']
๊ฐ์ฒด ๋์คํธ๋ญํ
let user = { name: "Ram", age: 20, salary: '20K', job: 'Tester' };
let { name, age, ...details } = user;
name; // Ram
age; // 20
details; // { salary: '20K', job: 'Tester' };
6.Convert NodeList Object to Array
๋
ธ๋ ๋ฆฌ์คํธ๋ ๋ฐฐ์ด๊ณผ ๋น์ทํ์ง๋ง ๋ฐฐ์ด์ ๋ชจ๋ ๋ฉ์๋๋ฅผ ๊ฐ์ง๊ณ ์๋ ๊ฒ์ ์๋๋๋ค. forEach
, map
, filter
๋ฑ์ด ์์ฃ .
let nodeList = document.querySelectorAll('.class')
var nodeArray = [...nodeList]
7.Convert String to Character
๋ฌธ์์ด๋ ์ํ ๊ฐ๋ฅํ ๊ฐ์ฒด์ด๊ธฐ ๋๋ฌธ์ ์คํ๋ ๋ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
let name = "Ram";
let chars = [...name]; //['R', 'a', 'm']
8.Eliminate Duplicates From an array
let num = [1, 3, 1, 3, 3, 1];
let uniqueNum = [...new Set(num)];
uniqueNum; //[ 1, 3]
Summary
- ์คํ๋ ๋ ์ฐ์ฐ์ ํ์ฉ๋ฒ ๋ณต์ต