프로그래밍 공부 메모/nodejs

매개변수 패턴 - 구조 분해 할당(객체 / 배열)

jjs815 2023. 6. 25. 22:17

[ 객체 구조 분해 할당 ]


const user = {
    name : 'jjs',
    age : 18
}

function getName(user){
    const { name } = user //user 객체의 name 속성 값만 가져옴
    return name
}

console.log(getName(user)) // jjs 출력

 

getName({name}) 함수 선언 시 user 객체의 name 속성 값을 바로 넣을 수 있음


const user = {
    name : 'jjs',
    age : 18
}

function getName({name}){
    return name
}

console.log(getName(user)) // jjs 출력

[배열 구조 분해 할당]

const furits=['apple', 'banana', 'cherry']

function getSecondItem(arry){
    return arry[1]
}

console.log(getSecondItem(furits)) // banana 출력
const furits=['apple', 'banana', 'cherry']

function getSecondItem([a,b,c]){  
    return b
}

console.log(getSecondItem(furits)) // banana 출력

const furits=['apple', 'banana', 'cherry']

function getSecondItem([,b]){  
    return b
}

console.log(getSecondItem(furits)) // banana 출력

[나머지 매개변수]

하나의 함수에 매개변수가 어려개 일 때 (undefined가 중간중간 출력 되는 것은 return 키워드가 돌려주는 값)

function sum(...rest){
    console.log(rest)
}

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

 

function sum(a,b,...rest){
    console.log(rest)
}

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

 

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

반응형