1. 程式人生 > >[Algorithms] Refactor a Loop in JavaScript to Use Recursion

[Algorithms] Refactor a Loop in JavaScript to Use Recursion

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.

  Resurison sometime is easier to find a value in deep nested array.
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"