[Algorithms]Refactor a Loop in JavaScript to Use Recursion

1359 ワード

Recursion is when a function cals itself.This self caling function handleast two cases,the recursive case and the base case.People seem to eigther love it hate it because it can be difficult to undersstand and implement corectly.Let’s walk through a recursive function and factor a looptime the the funce the forept the sant stant the forrererererererect per.
 
Reurison sometime is easure to find a value in deep ness ted 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"
 
転載先:https://www.cnblogs.com/Answer1215/p/10129338.html