Notice
Recent Posts
Recent Comments
Link
솔미는 성장중
[JS] 함수 : 재귀 본문
728x90
하나의 함수에서 함수 자기 자신을 내부에서 다시 호출하는 것
기본적으로 무한 동작하기 때문에 필요할 때 멈춰줄 수 있게 만들어줘야 한다.
예시) 재귀 함수를 통해 최상위 포식자 찾기
const animalA = {name: 'A', predator: null}
const animalB = {name: 'B', predator: animalA}
const animalC = {name: 'C', predator: animalB}
const getFinalPredator = animal => {
if(animal.predator){
return getFinalPredator(animal.predator)
}
return animal.name //A
}
console.log(getFinalPredator(animalC))
흐름
getFinalPredator함수에 인자로 animalC를 넣는다.
만약 animalC의 객체 데이터에서 predator가 있으면 if문이 실행된다.
if문이 실행되면 animal.predator에 해당하는 값을 다시 넣어준다. (재귀)
~반복~
결과적으로 최상위 포식자인 animalA의 name이 출력된다.
728x90
'JavaScript > 함수' 카테고리의 다른 글
[JS] This (0) | 2023.07.18 |
---|---|
[JS] 호출 스케줄링 ( 타이밍 함수 ) (0) | 2023.07.18 |
[JS] 콜백 (callback) 함수 (예시 포함) (0) | 2023.07.18 |
[JS] 즉시 실행 함수 (IIFE) (0) | 2023.07.18 |
[JS] 함수 선언 : 화살표 함수 (0) | 2023.07.18 |