ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 매개변수 패턴 - 구조 분해 할당(객체 / 배열)
    프로그래밍 공부 메모/nodejs 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

    반응형

    '프로그래밍 공부 메모 > nodejs' 카테고리의 다른 글

    javascript event loop 동작 흐림도  (0) 2023.08.19
    PM2 - Node.js 프로세스 관리 도구  (0) 2023.08.19
    javascript 반복문 예제  (0) 2023.08.13
    for 반복문(of / in 사용법)  (0) 2023.06.25
    ?? 연산자  (0) 2023.06.25
Designed by Tistory.