
인수 객체는 '유사 배열 객체'라고도 불린다.
--> 요소에 접근하려면 인덱스를 사용해야 함.
배열 메서드를 사용할 수 없다.
--> push, pop, reduce 메서드 사용 불가.
인수 객체는 함수로 전달된 인수를 모두 가지고 있다.
ex)
function sum(nums) = {
console.log(arguments)
}
sum(34, 65, 77)
> Arguments(3) [34, 65, 77, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// 위 함수에선 배열 메스드 중 일부인 reduce메서드 사용불가 ==> 배열 메서드가 아니기 때문
나머지 연산자는 점 3개로
...만들며, 매개변수 자리에 들어간다.
후에 남아있는 인수를 모두 모아 배열로 출력하게 된다.
function sum(...nums) {
return nums.reduce((total, el) => total + el)
}
sum(2,3,1)
> 6
function olympicRank(gold, silver, bronze, ...another){
console.log(`금메달: ${gold}`)
console.log(`은메달: ${silver}`)
console.log(`동메달: ${bronze}`)
console.log(`탈락: ${another}`)
}
olympicRank('철수', '유리', '짱구', '훈이', '맹구')
> 금메달: 철수
은메달: 유리
동메달: 짱구
탈락: 훈이, 맹구
값을 해체하고 꺼내고 선정하는 방식.
// 배열로 이루어진 게임 점수
const scores = [98, 87, 77, 72, 63, 43, 21]
// 1위 점수 꺼내기
const firstRank = scores[0]
// 2위 점수 꺼내기
const secondRank = scores[1]
//분해 구문 이용
const [first, second, third] = scores
first
> 98
second
> 87
third
> 77
// 나머지 순위 분해구문을 통해 출력해보기
const [first, second, third, ...another] = scores
another
> [72, 63, 43, 21]
배열 분해와 달리 순서를 따르지 않아 실용적으로 사용가능
const user = {
email: 'abc123@naver.com',
password: 'abcd1234'
firstName: 'Kim',
lastName: 'Chulsoo',
born: 1923,
died: 2008,
city: Mapo
}
const {email, fisrtName, lastName} = user;
// 결과값 출력
email
> abc123@naver.com
firstName
> Kim
lastName
> Chulsoo
즉, 객체의 값을 기반으로 한 다섯 개의 새 변수를 만들게 된 것이다.
// 출생년도, 사망년도를 새로운 변수로 저장
const { born: birthYear, died: deathYear} = user; // born을 birthYear로 대체하고, born의 값을 birthYear에 값을 준다고 생각하며 된다.
user2 = {
email: 'lucky0132@naver.com',
firstName: 'Lee',
lastName: 'Dajung',
birth: 2003;
city: 'Gangnam'
hometown: 'Seoul'
}
const { city, hometown, died = 'N/A' } = user2;
died
> N/A
// 반대로 user의 died 값을 'N/A'로 바꿔주면?
const { died = 'N/A' } = user;
died
> 2008
N/A가 적용되지 않았을까?함수의 매개변수에 적용되는 분해이다.
function fullName(user) {
const { fistname, lastName } = user;
return `${firstName} ${lastName}`
}
// 객체에 적힌 정보 활용이 필요없이 그저 이름만 출력하고자 할때 매개변수 분해를 통해 추출하기
function fullName({firstName, lastName}) {
return `${firstName} ${lastName}`
}
fullName(user)
> Kim Chulsoo
const movies = [
{
title: '기생충',
score: 95,
year: 2019
},
{
title: '아바타2',
score: 93,
year: 2022
},
{
title: '극한직업',
score: 92,
year: 2019
},
{
title: '설국열차',
score: 88,
year: 2015
},
{
title: '영웅',
score: 83,
year: 2022
},
{
title: '허삼관',
score: 78,
year: 2016
}
]
// 90점 이상 영화 필터를 통해 추출
movies.filter((movie) => movie.score > 90)
// 위의 식 구조분해
movies.filter(({ score }) => score > 90)
//title, year, score 모두 출력
movies.map(movie => {
return `${movie.title} (${movie.year})의 평점은 ${movie.score} 입니다.`
})
// 위의 식 구조분해
movies.map(({title, year, score}) => {
return `${title}(${year}) 의 평점은 ${score}`
})