[JavaScript] ์ฃผ์š” ๋ฌธ๋ฒ•

๋””๋”ฉยท2022๋…„ 11์›” 8์ผ
0

Section

๋ชฉ๋ก ๋ณด๊ธฐ
15/18
post-thumbnail

๐Ÿ•– DAY +14 / 2022. 11. 08

SEB FE / Section1 / Unit9 / JavaScript ํ•ต์‹ฌ ๊ฐœ๋…๊ณผ ์ฃผ์š” ๋ฌธ๋ฒ•



๐Ÿ“Œ Today I Learned

  • ES6

๐Ÿ’ฌ ES6

๐Ÿ“‚ spread/rest ๋ฌธ๋ฒ•

spread ๋ฌธ๋ฒ•

์ฃผ๋กœ ๋ฐฐ์—ด์„ ํ’€์–ด์„œ ์ธ์ž๋กœ ์ „๋‹ฌํ•˜๊ฑฐ๋‚˜, ๋ฐฐ์—ด์„ ํ’€์–ด์„œ ๊ฐ๊ฐ์˜ ์š”์†Œ๋กœ ๋„ฃ์„ ๋•Œ์— ์‚ฌ์šฉํ•œ๋‹ค.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

sum(...numbers) // ์งˆ๋ฌธ: ์–ด๋–ค ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋Š”๊ฐ€?

rest ๋ฌธ๋ฒ•

ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐฐ์—ด์˜ ํ˜•ํƒœ๋กœ ๋ฐ›์•„์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ€๋ณ€์ ์ผ ๋•Œ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

sum(1,2,3) // ์งˆ๋ฌธ: ์–ด๋–ค ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋Š”๊ฐ€?
sum(1,2,3,4) // ์งˆ๋ฌธ: ์–ด๋–ค ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋Š”๊ฐ€?

`...args`๋Š” `rest parameter`, `rest syntax`๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค.

๋‚จ์•„์žˆ๋Š” ๋ชจ๋“  ์ธ์ž๋ฅผ ํ•˜๋‚˜์˜ ๋ฐฐ์—ด์— ๋‹ด๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ ‡๊ฒŒ ๋ถ€๋ฅธ๋‹ค.

function printMaxNums(...args) {
  console.log(args)
}

์‹คํ–‰์ด ๋˜๋ฉด rest parameter args๋Š” ๋ชจ๋“  ๋‚จ์•„์žˆ๋Š” ์ธ์ž๋ฅผ ํ• ๋‹น๋ฐ›๋Š”๋‹ค. ๋”ฐ๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋นผ๋†“์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ args๋Š” ๋ฐฐ์—ด์˜ ํ˜•ํƒœ๋กœ ๋ชจ๋“  ์ธ์ž๋ฅผ ํ• ๋‹น ๋ฐ›๋Š”๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋‹ต์€ [10, 30, 40], A์ด๋‹ค

function printMaxNums(num1, ...args) {
  console.log(args) // [30, 40]
}

๋”ฐ๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ง€์ •ํ–ˆ์—ˆ๋‹ค๋ฉด, ๋‚จ์€ ๋งค๊ฐœ๋ณ€์ˆ˜๋งŒ ๋ฐฐ์—ด์˜ ํ˜•ํƒœ๋กœ rest parameter args์— ํ• ๋‹นํ•œ๋‹ค.

๐Ÿ“‚ ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น

๋ฐฐ์—ด

const [a, b, ...rest] = [10, 20, 30, 40, 50];

// ์งˆ๋ฌธ: a, b, rest๋Š” ๊ฐ๊ฐ ์–ด๋–ค ๊ฐ’์ธ๊ฐ€?

๊ฐ์ฒด

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// ์งˆ๋ฌธ: a, b, rest๋Š” ๊ฐ๊ฐ ์–ด๋–ค ๊ฐ’์ธ๊ฐ€?

๊ฐ์ฒด์—์„œ ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ, ์„ ์–ธ(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) // ์งˆ๋ฌธ: ์ฝ˜์†”์—์„œ ์–ด๋–ป๊ฒŒ ์ถœ๋ ฅ๋ ๊นŒ?
profile
๋ฌด์‚ฌ์™€์š”... ์—ด๊ณตํ–์š”...

0๊ฐœ์˜ ๋Œ“๊ธ€