函数在内部自己调用自己是递归,需要叫上判断条件来终止递归的运行。
一.用递归求1-10的和
if (a === 1) {
return 1;
}
return a + fn(a - 1);
}
const res = fn(10);
// 4+3+2+1
console.log(res);
当等于10时候
10+fn(9)
10+9+fn(8)
10+9+8+fn(7)
....
10+9+8+2+...fn(1)
当a=1的时候返回一个1终止递归的运行。
二.猴子吃桃问题
一只小猴子一天摘了许多桃子,第一天吃了一半,然后忍不住又吃了一个;第二天又吃了一半,再加上一个;后面每天都是这样吃。到第10天的时候,小猴子发现只有一个桃子了。问小猴子第一天共摘了多少个桃子。
这里用到了逆向思维:
设第九天还剩下x个桃子:
x/2-1=1
x=4
第几天还剩下4个桃子。
据此推理那么第八天:
(4+1)x2=10
第八天剩下10个桃子
// 设第一天剩1个
1 //第十天
4 // 第九天
10 //第八天
22 //第七天
46 //第六天
94 //第五天
190 //第四天
382 //第三天
766 //第二天
1534 //第一天
推导出:
var a = 1;
function num(n) {
a++;
if (a === 11) {
return n;
}
// debugger
return num((n + 1) * 2);
}
const res = num(1);
console.log(res)
打印的结果:
不借用外部变量使用递归:
function num(n,m) {
if (m ===1) {
return n;
}
// debugger
return num((n + 1) * 2,m-1);
}
const res = num(1,10);
console.log(res);
三.树形数据转换
const arr = [
{ 'id': '29', 'pid': '', 'name': '总裁办' },
{ 'id': '2c', 'pid': '', 'name': '财务部' },
{ 'id': '2d', 'pid': '2c', 'name': '财务核算部'},
{ 'id': '2f', 'pid': '2c', 'name': '薪资管理部'},
{ 'id': 'd2', 'pid': '', 'name': '技术部'},
{ 'id': 'd3', 'pid': 'd2', 'name': 'Java研发部'}
]
function fn(arr,str=''){
// 这里的return是返回给函数
return arr.filter(item=>{
if (item.pid==str) {
// 拿到第一层数据
item.children=fn(arr,item.id)
return true
}
})
}
const res= fn(arr)
console.log(res);
找出第一层:
重新调用函数:
传入自己的id和数组里面的进行筛选
如果和数组里面的pid相等
那么当前项的children的pid和上一项的id想等。