JavaScript 递归 ,场景:比如后端传来的数据菜单列表不知道是多少层的

 

 

 

https://www.programiz.com/javascript/online-compiler/?ref=f8e51c16

 

 

使用递归

例子:数的阶乘

// program to find the factorial of a number
function factorial(x) {

    // if number is 0
    if (x === 0) {
        return 1;
    }

    // if number is positive
    else {
        return x * factorial(x - 1);
    }
}

const num = 3;

// calling factorial() if num is non-negative
if (num > 0) {
    let result = factorial(num);
    console.log(`The factorial of ${num} is ${result}`);
}

 

posted @ 2023-06-01 16:10  漫漫长路</>  阅读(4)  评论(0编辑  收藏  举报