The notion of recursion

That is, a function calls itself, or calls itself from a function that is a descendant of its own function.

Recursive steps

  1. So let’s say the recursive function is already written
  2. Look for recursive relationships
  3. Transform the structure of a recursive relationship into a recursive body
  4. Add critical conditions to the recursive body

Classic case # 1: Summation

And for 1-100

function sum(n) {
  if (n == 1) return 1
  return sum(n - 1) + n
}
Copy the code

Classic case 2: The Fibonacci series

1,1,2,3,5,8,13,21,34,55,89… O n

// Recursive method
function fib(n) {
  if (n === 1 || n === 2) return n - 1
  return fib(n - 1) + fib(n - 2)}console.log(fib(10)) / / 34

// Non-recursive method //
function fib(n) {
  let a = 0
  let b = 1
  let c = a + b
  for (let i = 3; i < n; i++) {
    a = b
    b = c
    c = a + b
  }
  return c
}
console.log(fib(10)) / / 34
Copy the code

Classic case # 3: Taking the stairs

If a staircase has n steps, each time you can take 1 or 2 steps, how many ways can you take to complete the n steps

function climbStairs(n) {
  if (n == 1) return 1
  if (n == 2) return 2
  return climbStairs(n - 1) + climbStairs(n - 2)}Copy the code

Classic case 4: Deep copy

Clone (o) = new Object; Return an object

function clone(o) {
  var temp = {}
  for (var key in o) {
    if (typeof o[key] == 'object') {
      temp[key] = clone(o[key])
    } else {
      temp[key] = o[key]
    }
  }
  return temp
}
Copy the code

Classic case 5: Recursive components

  • Recursive components: A component can recursively call itself within its template by setting the name component to the component.
  • Note, however, that you must give a condition to limit the number, otherwise an error will be raised: Max Stack Size exceeded
  • Component recursion is used to develop independent components that have an unknown hierarchy. Examples include cascading selectors and tree controls
<template> <div v-for="(item,index) in treeArr"> {{index}} <br/> <tree :item="item.arr" v-if="item.flag"></tree> </div> Name: 'tree', data(){return {}}, // props for receiving external values: { item: { type:Array, default: ()=>[] } } } </script>Copy the code