Notice
Recent Posts
Recent Comments
Link
솔미는 성장중
[JS] 함수 : 구조 분해 할당 본문
728x90
💻 객체 구조 분해 할당
const user = {
name: 'solmi',
age: 99
}
function getName(user) {
return user.name
}
console.log(getName(user))
//solmi
const user = {
name: 'solmi',
age: 99
}
function getName(user) {
const { name } = user
return name
}
console.log(getName(user))
//solmi
const user = {
name: 'solmi',
age: 99
}
function getName({ name }) {
return name
}
console.log(getName(user))
//solmi
- 이 예시에 주목하기
const user={
name: 'solmi',
age: 99,
email: 'ovo10203@gmail.com'
}
const {name, age, address} = user //필요한 것만 꺼내서 쓰면 됨! ex) name만 가져나와도 됨.
console.log(`사용자 이름은 ${name}`) // 사용자 이름은 solmi
console.log(`나이는 ${age}`) // 나이는 99
console.log(`이메일 주소는 ${user.email}`) // 이메일 주소는 ovo10203@gmail.com
console.log(address) //undefined
- undefined 상태면 기본값이 출력됨.
const user = {
name: 'solmi',
age: 99
}
function getName({ name }) {
return name
}
function getEmail({ email = "이메일이 없습니다" }) {
return email
}
console.log(getName(user)) // solmi
console.log(getEmail(user)) // 이메일이 없습니다
- 다른 이름으로 가지고 나오고 싶으면 '콜론'을 사용해주자
const user={
name: 'solmi',
age: 99,
email: 'ovo10203@gmail.com'
}
const {name: nickname, age, address} = user //name 부분 주목!!!!!!!!!!!!!!!!!
console.log(`사용자 이름은 ${nickname}`) // 사용자 이름은 solmi
💻 배열 구조 분해 할당
(객체와 다르게 대괄호 사용해야함)
const fruits = ['Orange','Peach','Apple']
function getSecondItem(array){
return array[1]
}
console.log(getSecondItem(fruits))
//Peach
const fruits = ['Orange','Peach','Apple']
function getSecondItem([a,b,c]){
return b
}
console.log(getSecondItem(fruits))
//Peach
이때 getSecondItem함수를 다음과 같이 바꿔도 된다.
- 쉼표를 통해 b가 몇 번째 아이템인지 알려준다.
function getSecondItem([,b]){
return b
}
다른 예시)
const fruits = ['Orange','Peach','Apple']
const [a,b,c,d] = fruits
console.log(a,b,c,d)
//Orange Peach Apple undefined
💻 전개 연산자
const fruits = ['Apple','Banana','Peach']
console.log(...fruits) //Apple Banana Peach = 배열 데이터를 쉼표로 구분해서 전개할 수 있음.
function toObject(a,b,c){
return{
a: a,
b: b,
c: c
}
}
console.log(toObject(...fruits)) //console.log(toObject(fruits[0],fruits[1],fruits[2]))랑 같음
//a:"Apple"
//b:"Banana"
//c:"Peach"
💻 나머지 매개변수
전개 연산자를 나머지 모든 변수를 받는 용도로 사용할 수도 있음.
function sum(...rest){
console.log(rest)
return rest.reduce(function(acc,cur){
return acc+cur
}, 0)
}
console.log(sum(1,2))//3
console.log(sum(1,2,3,4)) //10
console.log(sum(1,2,3,4,5,6,7,8,9,10)) //55
해석
...rest
: 인수를 배열의 형태로 가져와 준다.
: ...은 전개 연산자
🎃 만약 (a,b, ...rest) 라면?
: 1번째 인수는 a에, 2번째 인수는 b에, rest에는 나머지 모든 것을 배열의 형태로.
reduce 메소드
: 배열 데이터의 아이템 개수만큼 callback 함수를 실행
acc
: 누적시킨 값을 담을 변수, 최조값은 콜백 함수 뒤에 적힌 숫자 (0)
cur
: current를 의미하며 배열에서 갖고온 값 (예제에서 첫 번째는 1)
다른 예시)
const fruits = ['Apple','Banana','Peach', 'Cherry']
console.log(...fruits) //Apple Banana Peach = 배열 데이터를 쉼표로 구분해서 전개할 수 있음.
function toObject(a,b,..c){
return{
a: a,
b: b,
c: c
}
}
console.log(toObject(...fruits))
//a:"Apple"
//b:"Banana"
//c: Array(2) 0:"Peach" 1:"Cherry"
참고)
객체 데이터에서 key 값과 value 값이 같을 때 축약할 수 있다.
function toObject(a,b,..c){
return{
a,
b,
c
}
}
더 축약해보면
const toObject = (a,b,..c) => ({a, b, c})
💻 arguments → 유사 배열 (Array - Like)
function sum(...rest){
console.log(arguments)
}
console.log(sum(1,2))
//Arguments(2) [1, 2, callee: (...), Symbol(Symbol.iterator): ƒ]
// undefined
console.log(sum(1,2,3,4))
// Arguments(4) [1, 2, 3, 4, callee: (...), Symbol(Symbol.iterator): ƒ]
// undefined
console.log(sum(1,2,3,4,5,6,7,8,9,10))
// Arguments(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, callee: (...), Symbol(Symbol.iterator): ƒ]
// undefined
console.log(arguments)는 배열과 비슷하게 출력됨
0번째 숫자 1, 1번째 숫자 2, 2번째 숫자 3, ... 그리고 length 까지!
하지만 배열은 아니다!
'배열 데이터 처럼 생긴 객체'이다!!
배열 데이터가 아니기 때문에 reduce 메소드 사용 불가
728x90
'JavaScript > 함수' 카테고리의 다른 글
[JS] 함수 : 재귀 (0) | 2023.07.18 |
---|---|
[JS] 콜백 (callback) 함수 (예시 포함) (0) | 2023.07.18 |
[JS] 즉시 실행 함수 (IIFE) (0) | 2023.07.18 |
[JS] 함수 선언 : 화살표 함수 (0) | 2023.07.18 |
[JS] 함수 : 호이스팅 (함수 선언문, 함수 표현식) (0) | 2023.07.18 |