๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] Spread ์—ฐ์‚ฐ์ž(...)์˜ ํ™œ์šฉ

by YWTechIT 2021. 7. 12.
728x90

๐Ÿ“ Spread ์—ฐ์‚ฐ์ž(...)์˜ ํ™œ์šฉ

TS(TypeScript)๋ฅผ ๊ณต๋ถ€ํ•˜๋‹ค๊ฐ€ Spread๋ฅผ ๋‹ค์–‘ํ•œ ๊ณณ์— ์‚ฌ์šฉํ•จ์„ ๊นจ๋‹ซ๊ณ  ์ •๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ๊ธ€์„ ๋‚จ๊ธด๋‹ค. ๋Œ€์ฒด๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ƒํ™ฉ์—์„œ ์ž์ฃผ ์“ฐ์ธ๋‹ค.

  1. ๊ฐ์ฒด ๋ณต์‚ฌ(์ฃผ์†Œ ์ฐธ์กฐ๊ฐ€ ์•„๋‹Œ ๊ฐ’ ๋ณต์‚ฌ, origin ๊ฐ’ ๋ณ€๊ฒฝ X)
  2. ๊ฐ์ฒด ๋ณ‘ํ•ฉ(์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ์ฒด๋ฅผ ํ•˜๋‚˜์˜ ๊ฐ์ฒด๋กœ ํ•ฉ์น  ์ˆ˜ ์žˆ๋‹ค.)
  3. ๊ฐ์ฒด ํŠน์ • ๊ฐ’ ๋ณ€๊ฒฝ(useState ์‚ฌ์šฉ ์‹œ, ๋ถˆ๋ณ€์„ฑ์„ ์œ ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ํŠน์ • ๊ฐ’๋งŒ `update`ํ•˜๋Š” ๋ฐฉ๋ฒ•)
  4. ์ž”์—ฌ ์—ฐ์‚ฐ์ž(rest operator) ์‚ฌ์šฉ(ํŠน์ • ๊ฐ’์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€๋ฅผ ๋ณ„๋„์˜ ๋ณ€์ˆ˜์— ์ €์žฅํ•˜๊ณ  ์‹ถ์„ ๋•Œ)
728x90

๋‹ค์Œ์˜ ์ฝ”๋“œ๋ฅผ ํ•˜๋‚˜์”ฉ ์‚ดํŽด๋ณด์ž.

// 1. ๊ฐ์ฒด ๋ณต์‚ฌ

// * spread ์—ฐ์‚ฐ์ž ๋ฏธ ์‚ฌ์šฉ(์ฃผ์†Œ ์ฐธ์กฐ, ๋ณธ๋ž˜์˜ ๊ฐ’์ด ๋ฐ”๋€๋‹ค.)
const myScore = [80, 85, 90];
const newScore = myScore
newScore[0] = 50
console.log(myScore)
๐Ÿ‘‰๐Ÿฝ [50, 85, 90]

// * spread ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ(๊ฐ’ ์ฐธ์กฐ, ๋ณธ๋ž˜์˜ ๊ฐ’์ด ๋ฐ”๋€Œ์ง€ ์•Š๋Š”๋‹ค.)
const myScore = [80, 85, 90];
const newScore = [...myScore];
newScore[0] = 50
console.log(myScore)
๐Ÿ‘‰๐Ÿฝ [80, 85, 90]

// * ๊ฐ์ฒด ๋ณต์‚ฌ
const myInfo = {name: 'AYW', age:27,  marriage: false}
const newInfo = {...myInfo}
console.log(newInfo)
๐Ÿ‘‰๐Ÿฝ {name: 'AYW', age:27,  marriage: false}

// 2. ๊ฐ์ฒด ๋ณ‘ํ•ฉ
const firstInfo = {name: 'AYW'}
const secondInfo = {age: 27}
const resultInfo = {...firstInfo, ...secondInfo}
console.log(resultInfo)
๐Ÿ‘‰๐Ÿฝ {name: 'AYW', age:27}

// 3. ๊ฐ์ฒด ํŠน์ • ๊ฐ’ ๋ณ€๊ฒฝ
const myInfo = {name: 'AYW', age:27,  marriage: false}
const newInfo = {...myInfo, marriage: !myInfo.marriage}
console.log(newInfo)
๐Ÿ‘‰๐Ÿฝ {name: 'AYW', age:27,  marriage: true}

// 4. ์ž”์—ฌ ์—ฐ์‚ฐ์ž(spread operator) ์‚ฌ์šฉ
const myInfos = {money: 3000, name: 'AYW', age:27, }
const {money, ...restInfo} = myInfos
console.log(restInfo)
๐Ÿ‘‰๐Ÿฝ {name: 'AYW', age:27}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€