递归

作者: 栀丿東 | 来源:发表于2022-04-18 11:53 被阅读0次

    数字求和

        function sum(n){

          if(n===1){

            return n=1

          }

          return n+sum(n-1)  

    }

    每次执行

    5+sum(n-1)  //n=5

    5+4+sum(n-1) //n=4

    5+4+3+sum(n-1)  //n=3

    5+4+3+2+sum(n-1) //n=2

    5+4+3+2+1+sum(n-1) //n=1

    5+4+3+2+1

    console.log(sum(5)); //15


    数组求和

         function sum(arr) {

            var len = arr.length

            if (len == 0) {

              return 0

            } else if (len == 1) {

              return arr[0]

            } else {

              return arr[0] + sum(arr.slice(1))  //每一次调用就把数组的第一项去除再次传入进去

            }

          }

          let arr = [ 1, 2, 3, 4, 5 ]  

    每次执行

    1+sum(2,3,4,5)

    1+2+sum(3,4,5)

    1+2+3+sum(4,5)

    1+2+3+4+sum(5)

    1+2+3+4+5

    1+2+3+9

    1+2+12

    1+14

          console.log(sum(arr))


    数组转树

            let data = [{

                    id: "01",

                    pid: "",

    "name": "老王"

                },

                {

                    id: "02",

                    pid: "01",

    "name": "小张"

                }


            ]

      function fn(data, rootId = '') {

    const children = []      //定义一个空数组

                data.forEach(item => {

    if (item.pid === rootId) {    //如果每一项的pid=rootId就添加到数组里

                        children.push(item)

                        item.children = fn(data, item.id)

                    }

                });

                return children

            }

    相关文章

      网友评论

          本文标题:递归

          本文链接:https://www.haomeiwen.com/subject/bahdertx.html