[Algorithms] Refactor a Loop in JavaScript to Use Recursion
阿新 • • 發佈:2018-12-17
Recursion is when a function calls itself. This self calling function handles at least two cases, the recursive case and the base case. People seem to either love it or hate it because it can be difficult to understand and implement correctly. Let’s walk through a recursive function and refactor a loop to instead perform the same result with a recursive function.
const items = [[1, 2, 3], [4, 5, 6]] function findSix(i) { let hasSix = "no!" i.forEach(a => { if (a === 6) { hasSix = "yes!" } if (Array.isArray(a)) { hasSix = findSix(a) } })return hasSix } console.log(findSix(items)) . // "yes"