javascript中怎么读懂递归函数,读懂递归函数的代码逻辑?

一直不能读懂javascript中的递归函数,不清楚里面的层层调用是什么逻辑?每次碰到递归函数就会晕。
比如下面一个javascript组合排序的代码,里面就是递归实现:

https://img4.mukewang.com/5be2a6630001e1e503090489.jpg

看了很多遍,都不知道它里面的实现逻辑是什么?也不知道怎么打断点分析代码,就是感觉反复调用,让人很晕,怎么办?
求javascript大神就拿上面这个例子帮忙分析下,代码逻辑怎么实现的?如果能读懂递归函数,后面再慢慢尝试写递归函数。

月关宝盒
浏览 482回答 1
1回答

慕森王

var arr = ['A','B','C','D',"E","F","G"];function show(arr,num){&nbsp; &nbsp; debugger&nbsp; &nbsp; var resultNum = 0;&nbsp; &nbsp; var iNow = 1;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if(num==1){&nbsp; &nbsp; &nbsp; &nbsp; return arr.length;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function change(arr,iNow){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for(var i=0;i<arr.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var result = arr.concat();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.splice(i,1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( iNow == num ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resultNum += result.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; change(result,iNow+1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; change(arr,iNow+1);&nbsp; &nbsp; return resultNum;}console.log(show(arr,5));打开控制台 执行一下, 按F10 逐步执行.某些人说调不出, 只能说头脑逻辑性不够. 不能怪方法不行.首先接触到一个递归, 先看函数内部做了什么, 看不懂, 调试一遍,看内部的不懂的函数或分支&nbsp;做了什么.在不明白, 说明你的智商只如嘲讽一般.其次这个函数目的就是算阶乘.!arr.length/!(arr.length - 5)&nbsp;叹号为阶乘
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript