js 递归 浅用

js的递归,看到了很多次,也见过很多次,但是每次手写都会出问题,只能看着别人的博客文章誊写,自己写个小案例,以后看着自己的誊写

 

誊写案例1:斐波那契数列

1                         // 递归斐波那契数列
2             const FnOne = (n)=>{
3                 if(n===1 || n===2 ){
4                     return 1
5                 }
6                 return FnOne( n - 1 ) + FnOne( n - 2 )
7             }
8             console.log(FnOne(8));
9                                 

誊写案例2:1~n的阶乘

1                         // 1~n的阶乘
2             const FnTwo = (n) => {
3                 if( n === 1 ){
4                     return 1
5                 }
6                 return n * FnTwo( n - 1 )
7             }
8             console.log(FnTwo(6));

誊写案例3:树形结构的数组扁平化返回

 1             // 遍历数组(树形转扁平)
 2             // 创建一个树形的数组
 3             let arrThr = [
 4                     {
 5                         name:'今生',age:18,
 6                         brother:[
 7                             {name:'往生',age:24},
 8                             {name:'未来',age:12},
 9                         ],
10                     },
11                     {
12                         name:'伯',
13                         age:12,
14                         brother:[
15                             {
16                                 name:'仲',
17                                 age:11,
18                                 brother:[
19                                         {
20                                             name:'叔',
21                                             age:10,
22                                             brother:[
23                                                     {name:'季',age:9},
24                                                     {name:'幼',age:6},
25                                                 ],
26                                         },
27                                     ],
28                             },
29                         ],
30                     },
31                 ]
32             
33             // 递归函数,将有brothr的对象的外层的属性拿出来单独添加到新数组,brother则继续调用这个函数,直到最后一个没有brother属性
34             const FnThr = (data) => {
35                 let newArr = []
36                 data.forEach(item => {
37                     // 有brother
38                     if(item.brother && item.brother.length){
39                         // 将除brother属性外的其他属性添加到新的数组
40                         newArr.push({name:item.name,age:item.age})
41                         // 有brother的继续调用方法
42                         const temp = FnThr(item.brother)
43                         if(temp.length){
44                             newArr.push(...temp)
45                         }
46                     }
47                     // 没有brother直接添加进新数组
48                     else if(!item.brother){
49                         newArr.push(item)
50                     }
51                 })
52                 return newArr
53             }
54             console.log(FnThr(arrThr))

 

posted @ 2022-08-06 13:13  伊人兮明眸秋水  阅读(181)  评论(0编辑  收藏  举报