한 걸음씩

[JS][Udemy] Params, Spread, Rest, Destructuring 본문

JS

[JS][Udemy] Params, Spread, Rest, Destructuring

winter17 2023. 3. 23. 22:50

1.  Default Params

► 기본 매개변수 

  • The old way
function multiply(a, b) {
  b = typeof b !== 'undefined' ? b : 1;
  return a * b;
}

console.log(multiply(7)) // 7
console.log(multiply(7, 3)) // 21

2.  Spread

  • Expands an iterables(array, string, etc.) into a list of arguments
  • 정보의 소스를 펼쳐서 다른 용도로 만드는 것
  • 배열 또는 반복 가능한 객체를 인수로 펼치거나, 배열 리터럴로 펼칠 수 있고, 객체를 펼쳐서 새로운 객체를 만들 수 있음

Spread In Function Calls

const nums = [9, 3, 2, 8]
console.log(Math.max(nums)) // NaN → 무엇을 spread 해야할지 모름
console.log(Math.max(...nums)) // 9 → 변수 앞에 ...을 붙이면 원하는 값 출력
console.log(Math.max(9, 3, 2, 8)) // 9

 

 

console.log('hello')
>> hello

// 인수 하나 하나로 분리됨 → 숫자 배열을 출력한 것과 같음
console.log(...'hello')
>> h e l l o

console.log('h', 'e', 'l')
>> h e l

 

Spread with Arrays 

const nums1 = [1, 2, 3]
const nums2 = [4, 5, 6]

// 아래의 출력값들은 변수에 저장하지 않았기 때문에 단순 펼치기만 한 것 
console.log([...nums1, ...nums2])
>> [1, 2, 3, 4, 5, 6]

console.log(['a', 'b', ...nums2])
>> ['a', 'b', 4, 5, 6]

console.log([...nums1,nums2, 7, 8, 9])
>> [1, 2, 3, Array(3), 7, 8, 9]

console.log([...'hello'])
>> ['h', 'e', 'l', 'l', 'o']

 

Spread with Object

  • 객체에 있는 특성을 복사해서 새로운 객체를 만드는 것
  • 객체를 복사하는 이유 : 라이브러리, react를 사용할 때 아주 중요!! 그래서 객체를 변형하지 않고 복사하는 방법을 배우는 것
  • 객체 여러개를 하나로 묶을 수 있음
const feline = {legs: 4, family: 'Felidae'}
const canine = {family: 'Caninae', furry: true}

const dog = {...canine, isPet: true}
console.log(dog)
>> {family: 'Caninae', furry: true, isPet: true}

const lion = {...feline, genus: 'Panthera'}
console.log(lion)
>> {legs: 4, family: 'Felidae', genus: 'Panthera'}

// 중복 요소가 있으면 뒤의 배열을 우선으로 함
const catDog = {...feline, ...canine}
console.log(catDog)
>> {legs: 4, family: 'Caninae', furry: true}
// 인덱스와 문자열을 펼쳐서 key-value형태로 출력 
{...[2, 3, 4]}
>> {0: 2, 1: 3, 2: 4}

{...'hello'}
>> {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}

3.  Rest

► The Arguments Object 

  • 인수객체는 함수로 전달된 인수를 모두 가지고 있음
  • arguments는 전달된 인수를 하나로 묶어줌
  • 배열과 비슷하지만 배열은 아님
function sumAll() {
  let total = 0
  for (let i = 0; i < arguments.length; i++)
  {     total += arguments[i]
  }
  return total
}
console.log(sumAll(8, 4, 3, 2)) // 17
console.log(sumAll(2, 3)) // 5

 

► Rest Params

  • 나머지 연산자는 점 세 개로 만들고 매개변수 목록에 들어감
  • 그러면 남아 있는 인수를 모두 모으고 배열로 나타냄
function sumAll(...nums) {
  let total = 0
  for (let n of nums) total += n
  return total 
}
console.log(sumAll(1, 2)) // 3
console.log(sumAll(1, 2, 3, 4, 5)) // 15

4.   Destructuring

  • 구조 분해 : 값을 해체하고 꺼내고 선정하는 간편한 방식
  • 해체해서 별개의 변수 형태로 만들 수 있음

► Array Destructuring

  • 배열 분해
const raceResults = ['Alice', 'Winter', 'Dana']

const [gold, silver, bronze] = raceResults
console.log(gold) // Alice
console.log(silver) // Winter
console.log(bronze) // Dana

const [fastest, ...everyoneElse] = raceResults
console.log(fastest) // Alice
console.log(everyoneElse) // ['Winter', 'Dana']

 

 Object Destructuring

  • 객체 분해
  • 순서를 따르지 않기 때문에 배열 구조 분해보다 실용적
const runner = {
  first: 'Alice',
  last: 'Winter',
  country: 'Korea',
  title: 'Good job you are winner!'
}

// const first = runner.first 이런 형태로 하나하나 불러와야하는데 
// 객체 분해를 이용하면 다음과 같이 편리하게 원하는 값을 가져올 수 있다
const {first, last, country} = runner


console.log(first) // Alice
console.log(last) // Winter
console.log(country) // Korea


// runner에 country가 없다면 N/A가 출력됨
// 객체의 값이 없을 때 출력될 디폴트 값
const {country : which = 'N/A'} = runner
console.log(which) // Korea

 

  Param Destructuring

  • 매개 변수 분해
  • 함수를 이해해야 사용할 수 있음
const fullName = ({first, last}) => {
    return ` ${first} ${last}`
}
const runner = {
  first: 'Alice',
  last: 'Winter',
  country: 'Korea',
}

console.log(fullName(runner)) // Alice Winter

 

 

'JS' 카테고리의 다른 글

[TIL] 2303024  (0) 2023.03.24
[JS][Udemy] DOM  (0) 2023.03.24
[JS][Udemy] Array Callback Methods  (0) 2023.03.22
[JS][Udemy] JavaScript Functions 2  (0) 2023.03.21
[JS][Udemy] JavaScript Functions 1  (0) 2023.03.20