[DAY - 23] 재귀함수, 고차함수, 내장함수(parseInt, parseFloat, isNaN, setTimeout, setInterval)

2023. 4. 4. 19:03·🔥 부트캠프-웹 개발 🔥/JavaScript
  • 재귀함수
  • 고차함수
  • 내장함수

1) 재귀함수

재귀함수는 함수 안에서 자기 자신을 호출하는 함수이다.

let cnt = 1;

const fn=()=>{
    console.log(`${cnt}번 호출`);
    cnt++;
    if(cnt>5){
        return;
    }
    fn();
}
fn();



1번 호출
2번 호출
3번 호출
4번 호출
5번 호출

fn함수를 정의한 뒤 맨 밑에서 호출을 하면 if문을 만족할 때까지 계속 실행하게 된다.

'use strict';

const fn = num =>{
    console.log(`${num} 호출`);
    num--;
    if(num==0){
        console.log(`${num} 호출 중단`)
        return
    }
    fn(num);
}
fn(10);



10 호출
9 호출
8 호출
7 호출
6 호출
5 호출
4 호출
3 호출
2 호출
1 호출
0 호출 중단

함수를 호출할 때 원하는 출력을 얻기 위해 매개변수 값을 정하고 호출할 수도 있다.

num이 10부터 하나씩 줄어들면서 0==0이 될 때 중단이 된다. 

 

const fn=(dan, i=1)=>{
    if(i>9){
        return;
    } else {
        console.log(`${dan}x${i}=${dan*i}`);
        fn(dan, i+1);
    }
}
fn(5);



5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45

fn함수의 변수 dan에 5를 넣어 구구단 5단이 출력되게 해 보았다.

 

2) 고차함수

고차함수는 함수를 전달받거나, 함수를 결과로 반환하는 함수이다.

고차함수의 원리를 적용시킨 것은 Array객체, map, forEach, find, filter 등이 있다고 한다.

'use strict';

function make(){
    return function() {
        console.log('인사하기');
    }
}
let x = make();
x();
// -----------------

function make2(name){
    return function(hi) {
        console.log(`인사하기2: ${name} ${hi}`);
    }
}
let x2 = make2('강호동');
x2('안녕');
// -----------------

function make3(name){
    function innerFn(hi) {
        console.log(`인사하기3: ${name} ${hi}`);
    }
    return innerFn;
}
let x3 = make3('이수근');
x3('안녕');



인사하기
인사하기2: 강호동 안녕
인사하기3: 이수근 안녕

x함수를 호출하면 make함수가 호출되어 make의 return값인 function함수를 출력하게 된다.

x2, x3함수는 name엔 이름이 hi엔 안녕이 출력된다.

 

'use strict';

const increment=()=>{
    let x = 0;
    return function(){
        console.log(x++);
    }
}

let count = increment();
count();
count();
count();
count();

console.log('===============');

const decrement=(x=5)=>{
    return function(){
        return x--;
    }
}

let num = decrement();
for (let i = 0; i < 5; i++) {
    console.log(num());  
}



0
1
2
3
===============
5
4
3
2
1

increment함수로 인해 x가 0부터 1씩 커지면 그 값을 count가 받아 4번 출력하게 되고, decrement함수는 x가 5부터 1씩 감소하는 것을 i가 0부터 증가하여 4가 될 때까지 총 5번 출력하게 된다.

 

3-1) 내장함수#1 parseInt, parseFloat

'use strict';

let n1 = '100';
let n2 = '200px';
let n3 = '123.456';
let n4 = '101동';
let n5 = '10살';

n1 = Number(n1);
n2 = parseInt(n2);
n3 = parseFloat(n3);
n4 = parseInt(n4);
n5 = parseInt(n5);

console.log(`출력: ${n1}, ${typeof n1}`);
console.log(`출력: ${n2}, ${typeof n2}`);
console.log(`출력: ${n3}, ${typeof n3}`);
console.log(`출력: ${n4}, ${typeof n4}`);
console.log(`출력: ${n5}, ${typeof n5}`);



출력: 100, number
출력: 200, number
출력: 123.456, number
출력: 101, number
출력: 10, number

parseInt는 문자를 제거하고 숫자(정수)가 되도로 만들어 주고 parseFloat는 소수점까지 숫자로 변환시켜 준다.

 

3-2) 내장함수#2 isNaN

NaN == NaN, NaN === NaN는 false로 인식하기 때문에 NaN를 판별하는 함수가 필요할 때 사용한다.

'use strict';

let a = 100;
let b = 123.456;
let c = 'Not a Number';
let d = 10*20;
let e = ' ';
let f = true;

console.log(`출력: ${typeof a}, ${isNaN(a)}`);
console.log(`출력: ${typeof b}, ${isNaN(b)}`);
console.log(`출력: ${typeof c}, ${isNaN(c)}`);
console.log(`출력: ${typeof d}, ${isNaN(d)}`);
console.log(`출력: ${typeof e}, ${isNaN(e)}`);
console.log(`출력: ${typeof f}, ${isNaN(f)}`);

let str1 = a + c;
let str2 = String(a) + String(b);
let str3 = Number(str2);
console.log(`${typeof str1}, ${isNaN(str1)}`);
console.log(`${typeof str2}, ${isNaN(str2)}`);
console.log(`${typeof str3}, ${isNaN(str3)}`);



출력: number, false
출력: number, false
출력: string, true
출력: number, false
출력: string, false
출력: boolean, false
string, true
string, false
number, false

숫자, 공백, 논리값 = false

문자, 문자+숫자 = true

 

3-3) 내장함수#3 setTimeout, setInterval

setTineout(함수, 시간)는 한 번만 실행되고 setInterval(함수, 시간)은 매 시간마다 계속 실행된다.

* 1초 = 1000

        setTimeout( function(){
            window.open('http://www.google.com');
        }, 3000)

 3초 뒤에 google페이지가 열리게 된다.

 

'🔥 부트캠프-웹 개발 🔥/JavaScript' 카테고리의 다른 글
  • [DAY - 25] charAt, slice, substring, toLowercase / toUppercase, concat, trim, indexOf, search, includes, split, replace, padstart
  • [DAY - 24] setInterval, dom, 객체, length
  • [DAY - 16] this, 매개변수, return, 화살표함수, 콜백함수
  • [DAY - 15] 탬플릿리터널, 함수(function), onclick
Yeonhub
Yeonhub
✨ https://github.com/yeonhub 📧 lsy3237@gmail.com
  • Yeonhub
    비 전공자의 Be developer
    Yeonhub
  • 전체
    오늘
    어제
    • 전체보기 (169)
      • 🔍 Tech 🔍 (19)
        • Front-End (11)
        • Back-End (4)
        • AI (1)
        • Server (1)
        • Etc (2)
      • 💡 원티드 프리온보딩 챌린지 💡 (14)
        • PRE-ONBOARDING_AI (11월) (1)
        • PRE-ONBOARDING_FE (2월) (2)
        • PRE-ONBOARDING_FE (1월) (2)
        • PRE-ONBOARDING_FE (12월) (9)
      • 🔥 부트캠프-웹 개발 🔥 (118)
        • HTML5 (7)
        • CSS3 (21)
        • JavaScript (27)
        • JavaScript_advanced (9)
        • React (24)
        • Next (1)
        • MYSql (5)
        • Node (5)
        • 오늘하날(개인프로젝트) (12)
        • 이젠제주투어(팀프로젝트) (7)
      • 💻 CS 💻 (1)
        • 알고리즘 (1)
      • ⚡ 코딩테스트 ⚡ (11)
        • JavaScript (11)
      • 📚 Books 📚 (6)
        • 클린 아키텍처 (2)
        • 인사이드 자바스크립트 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    라스콘
    expo map
    rn bottom sheet
    expo fcm
    react native firebase analytics
    라스콘4
    react native analytics
    rn admob
    expo google map
    expo deep linking
    php node
    node fcm
    expo fcm push
    프론트엔드 테스트코드
    bottom sheet
    expo admob
    node crontab
    react native expo fcm
    컴파운드 컴포넌트 패턴
    node.js fcm
    react vite
    node cron
    expo 지도
    Node
    react native bottom sheet
    expo 길찾기
    react native admob
    javascript fcm
    python node
    expo node fcm
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 23] 재귀함수, 고차함수, 내장함수(parseInt, parseFloat, isNaN, setTimeout, setInterval)
상단으로

티스토리툴바