Medium - 8 ways to use the Spread operator in JavaScript.

์›๋ฌธ - Javascript Jeep๐Ÿš™๐Ÿ’จ

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

  • ์Šคํ”„๋ ˆ๋“œ ์—ฐ์‚ฐ์ž ํ™œ์šฉ๋ฒ• ๋ณต์Šต

ยฉ 2019. All rights reserved.

Powered by Hydejack v8.1.1