递归是函数的高级用法,本质上是函数自已调用自已,它的行为非常类似循环
1.本质:自己调用自己如果一个函数内部调用自已本身,并且通过条件控制避免陷入死循环,这就是递归函数
2.递归要加结束条件: 不能一直调用自己吧?没完没了了吗?得结束啊
基础递归实例
1、使用递归打印1-10之间的数字
let i = 0;
function fn() {
//递归的结束条件
if (i >= 10) {
return
}
i++;
console.log(i);
fn()
}
fn();
2.利用递归求1 -10之间的和
let i = 0;//起始值
let sum = 0; //和
function fn() {
//递归结束条件
if (i >= 10) {
return sum;
}
i++;
sum += i;
//调用自身函数
fn();
}
fn();
console.log(sum);//55
深入递归取值
1、使用递归取单个值
// 递归取值
let data = {
"id": 30,
"roleName": "主管",
"roleDesc": "技术负责人",
"children": [
{
"id": 101,
"authName": "商品管理",
"path": null,
"children": [
{
"id": 104,
"authName": "商品列表",
"path": null,
"children": [
{
"id": 105,
"authName": "添加商品",
"path": null
}
]
}
]
}
]
}
// 去除添加商品四个字 即最好一个children属性内的authName
let dataArray = [];
function getAuthName(dataList) {
dataList.forEach(item => {
if (item.children) {
getAuthName(item.children);
}else{
return dataArray.push(item.authName);
}
});
}
getAuthName(data.children);
console.log(dataArray);
2、使用递归取多个值
let data = [
{
"id": 30,
"roleName": "主管",
"roleDesc": "技术负责人",
"children": [
{
"id": 101,
"authName": "商品管理",
"path": null,
"children": [
{
"id": 104,
"authName": "商品列表",
"path": null,
"children": [
{
"id": 105,
"authName": "添加商品",
"path": null
}
]
}
]
}
]
},
{
"id": 301,
"roleName": "主管1",
"roleDesc": "技术负责人1",
"children": [
{
"id": 1011,
"authName": "商品管理1",
"path": null,
"children": [
{
"id": 1041,
"authName": "商品列表1",
"path": null,
"children": [
{
"id": 1051,
"authName": "添加商品1",
"path": null
}
]
}
]
}
]
},
{
"id": 302,
"roleName": "主管1",
"roleDesc": "技术负责人2",
"children": [
{
"id": 1012,
"authName": "商品管理2",
"path": null,
"children": [
{
"id": 1042,
"authName": "商品列表2",
"path": null,
"children": [
{
"id": 1052,
"authName": "添加商品2",
"path": null
}
]
}
]
}
]
},
];
// 取出所有的三级 authName
let dataArray = [];
function getAuthName(dataList) {
dataList.forEach(item => {
if (item.children) {
getAuthName(item.children);
}else{
return dataArray.push(item.authName);
}
});
}
getAuthName(data);
console.log(dataArray);// ['添加商品', '添加商品1', '添加商品2']
递归是函数的高级用法,本质上是函数自已调用自已
递归函数特性
-
重复执行
-
调用自身
-
【必须】要有条件控制,避免死循环