当前位置:网站首页>Recursion - if the function calls itself internally, then the function is a recursive function & the effect is the same as that of the loop & the push condition return should be added, otherwise stack
Recursion - if the function calls itself internally, then the function is a recursive function & the effect is the same as that of the loop & the push condition return should be added, otherwise stack
2022-07-24 09:29:00 【viceen】
recursive —— The function calls itself internally , Then this function is a recursive function & The effect is the same as that of circulation & To add launch conditions return, Otherwise, stack overflow occurs , Cause a dead cycle & Recursively add attributes to objects in the array & toString() And random numbers
1、 Concept
A method calls itself in the execution process , It's called recursion
Be careful : Calling overloaded methods is not recursive , You can't just look at the method name
The key to recursion : Method call , The program will stop at the method call , Continue execution until the method returns
1.1、 Recursive usage scenarios
- A problem can be divided into several sub problems
- The sub problem after splitting is different from the original problem except for the size of the problem , The solution is the same
- There are termination conditions for recursion
Be careful : The so-called termination condition is without the help of any other function , You can directly know and find the answer to the question
Recursive code = Termination conditions + Current steps that can be achieved without any method + The remaining problems are solved in the same way
1.2、 Recursive function
One The function calls itself internally , So this function is Recursive function .
The function of recursive function is actually Same as the circulation effect .
- What cycle is afraid of most is dead cycle , Recursion is also easy to happen “ Stack overflow ” Error of , So we have to To add launch conditions return.
<script>
// Stack overflow errors will occur
function fun(){
fun();
}
fun();
</script>
Add return Exit conditions
<script>
// Output six times
var num = 0;
function fun() {
console.log("hello"); // It will output six times
if (num == 5) {
return; // The derivation condition must be added to recursion
} else {
num++;
}
fun();
}
fun();
</script>
2、 Use recursion instead of loops
Recursion is the operation of a function call itself .
// In turn, print 1~10
for (var i = 1; i <= 10; i++) {
console.log(i);
}
// Borrow recursive implementation
function fn(e) {
console.log(++e);
if (e === 10) {
return
}
fn(e)
}
fn(0)
- The above uses recursion to realize sequential output 1~10,e Initialize to 0, Print e++ So the output 1, When e And so on 10 It's over , Otherwise, continue to call the function itself , By analogy , Until the end condition .
For the sake of understanding , Example : Before calculating the elements in the array n Element product of .
1、 Use for loop , You can do this :
<script>
let list = [1,2,3,4,5,6]
function multiply(arr, n) {
var product = 1;
for (var i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
console.log(multiply(list,4)) ; // 24
</script>
2、 Recursive writing , Pay attention to the code multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]. This means that you can rewrite multiply To call itself without relying on a loop .
<script>
let list = [1,2,3,4,5,6]
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
console.log(multiply(list,4)) ; // 24
</script>
stay multiply In the function ,
n <= 0 when , return 1.
stay n Than 0 In the big case , The function will call itself , Parameters n The value of is n - 1.
The function continues to call in the same way multiply, until n <= 0 until .
therefore , All functions can return , The original multiply Return results .
Be careful : Recursive function when there is no function call ( In this case , When n <= 0 when ) There must be a jump out structure , Otherwise, it will never be completed .
3、 example
3.1、 Get each item of the array value value
<script>
let list = [2, 4, 6, 8]
// Print the array in sequence value value
// 1、for Circulation mode
for (var i = 0; i < list.length; i++) {
console.log(' loop ', list[i]); // 2 4 6 8
}
// 2、 recursively
function fn(arr, e) {
console.log(arr[e]); // 2 4 6 8
++e
if (e === arr.length) {
return
}
fn(arr, e)
}
fn(list, 0)
</script>
3.2、 Sum the first few digits of the array
<script>
let list = [1,2,3,4,5,6]
function sum(arr, n) {
// Just modify the code below this line
if(n<=0){
return 0;
}else if(n==1){
return arr[0]
}else{
return arr[n-1]+sum(arr,n-1)
}
// else if(n==1) return arr[0];
// else return arr[n-1]+sum(arr,n-1)
// Just modify the code above this line
}
console.log(sum(list,4)) ; // 10
</script>
3.3、 Add attributes or unique identifiers to each object in the object array
<script>
let list = [{
name: ' Xiaohong ', id: 0 }, {
name: ' Xiao Ming ', id: 1 }]
console.log(' original ',list);
// Print the array in sequence value value
// 1、for Circulation mode
for (var i = 0; i < list.length; i++) {
list[i].age = 'China'
list[i].ids = Math.random().toString(36).substr(2)
console.log(' loop ', list[i]);
}
// 2、 recursively
function fn(arr, e) {
arr[e].age = ' China '
arr[e].ids = Math.random().toString(36).substr(2)
console.log(' recursive ',arr[e]);
++e
if (e === list.length) {
return
}
fn(arr, e)
}
fn(list, 0)
</script>
recursive - Show

random number
console.log(Math.random()) // 0.8187707720153985
console.log(Math.random().toString(36)) // '0.tuchtcpa9h'
console.log(Math.random().toString(36).substr(2)) // 'tuchtcpa9h'
attach :toString Usage method
Number Type of toString() The method is special , Yes Default mode and base mode Two kinds of .
1、 Example of default mode :
<script type="text/javascript">
var num1 = 10;
var num2 = 10.0;
var num3 = 10.5;
alert(num1.toString());// Output 10
alert(num2.toString());// Output 10
alert(num3.toString());// Output 10.5
</script>
No matter what notation you use to declare numbers , The default mode only returns in decimal .
2、 Examples of base patterns :
<script type="text/javascript">
var num1 = 10.5;
alert(num1.toString(2));// Output 1010.1
alert(num1.toString(8));// Output 12.4
alert(num1.toString(16));// Output a.8
</script>
Obviously , Base mode is to convert numeric type into corresponding base .
3.4、 Object array , Take out the last layer children data
<script>
var data = [
{
name: " Everything ",
children: [
{
name: " Fruits ",
children: [{
name: " Apple ", children: [{
name: ' green apple ' }, {
name: ' Red apple ' }] }]
},
{
name: ' Staple food ',
children: [{
name: " Steamed Rice ", children: [{
name: ' Northern Rice ' }, {
name: ' Southern Rice ' }] }]
},
{
name: ' Articles for daily use ',
children: [
{
name: " Computer ", children: [{
name: ' Lenovo computer ' }, {
name: ' Apple computer ' }] },
{
name: " Tool class ", children: [{
name: " Hoe " }, {
name: " The hammer " }] },
{
name: " Articles for daily use ", children: [{
name: " The shampoo " }, {
name: " Shower gel. " }] }
]
}
]
}]
// demand : Take out the last layer children data
var recursiveFunction = function () {
// Anonymous function writing
var str = ''
var getStr = function (list) {
list.forEach(item => {
if (item.children) {
getStr(item.children)
} else {
str += item.name + ';'
}
})
}
getStr(data)
console.log(str) // green apple ; Red apple ; Northern Rice ; Southern Rice ; Lenovo computer ; Apple computer ; Hoe ; The hammer ; The shampoo ; Shower gel. ;
}
recursiveFunction()
</script>
边栏推荐
- ASI-20220222-Implicit PendingIntent
- Let's test 5million pieces of data. How to use index acceleration reasonably?
- Description of MATLAB functions
- Scarcity in Web3: how to become a winner in a decentralized world
- Foreign lead operation takes one month to collect money, and the sideline still needs it
- Practice 4-6 number guessing game (15 points)
- [don't bother to strengthen learning] video notes (II) 2. Write a small example of Q learning
- Detailed explanation of the whole process of R & D demand splitting | agile practice
- How to open the port number of the server, and the corresponding port of common network services
- dp最长公共子序列详细版本(LCS)
猜你喜欢

Little dolphin "transformed" into a new intelligent scheduling engine, which can be explained in simple terms in the practical development and application of DDS

What is the component customization event we are talking about?

js定位大全获取节点的兄弟,父级,子级元素含robot实例

DP longest common subsequence detailed version (LCS)

Android系统安全 — 5.2-APK V1签名介绍

Data center: started in Alibaba and started in Daas

云原生(十二) | Kubernetes篇之Kubernetes基础入门

Cloud primordial (12) | introduction to kubernetes foundation of kubernetes chapter

Why is TCP a triple handshake

The next stop of data visualization platform | gifts from domestic open source data visualization datart "super iron powder"
随机推荐
Why does TCP shake hands three times instead of two times (positive version)
Lung CT segmentation challenge 2017 dataset download and description
One click openstack single point mode environment deployment - preliminary construction
NVIDIA set persistent mode
Why is TCP a triple handshake
Practice 4-6 number guessing game (15 points)
Detailed LinkedList
One year after I came to Ali, I ushered in my first job change
[don't bother to strengthen learning] video notes (III) 3. SARS (lambda)
Understanding of magnetic parameters in Hall sensors
配置系统环境变量的时候误删了Path怎么办?
Android Version Description security privacy 13
How to open the port number of the server, and the corresponding port of common network services
Hands on deep learning (VII) -- bounding box and anchor box
ASI-20220222-Implicit PendingIntent
Introduction to common ansible modules
dp最长公共子序列详细版本(LCS)
唐宇迪opencv-背景建模
Android system security - 5.3-apk V2 signature introduction
Android system security - 5.2-apk V1 signature introduction