当前位置:网站首页>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>
边栏推荐
- 力扣300-最长递增子序列——动态规划
- The difference between & &, | and |
- TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
- Description of MATLAB functions
- NVIDIA set persistent mode
- Learning transformer: overall architecture and Implementation
- Data center: started in Alibaba and started in Daas
- Firewalld firewall related commands
- Re6: reading paper licin: a heterogeneous graph based approach for automatic legal stat identification fro
- SQL server2012 installation method details [easy to understand]
猜你喜欢

Leetcode94 detailed explanation of middle order traversal of binary tree

Opencv learning Day5

Scarcity in Web3: how to become a winner in a decentralized world

How to judge and analyze NFT market briefly through NFT go?

Lung CT segmentation challenge 2017 dataset download and description

Tiktok's "online celebrity" was poached by Amazon and broadcast on Amazon live platform

Tang Yudi opencv background modeling
![[the first anniversary of my creation] love needs to be commemorated, so does creation](/img/89/2f8eec4f0a0bcf77d5a91179012899.png)
[the first anniversary of my creation] love needs to be commemorated, so does creation

Protocol buffers 的问题和滥用

Android系统安全 — 5.2-APK V1签名介绍
随机推荐
Understanding of magnetic parameters in Hall sensors
Getting started with sorting - insert sorting and Hill sorting
详解LinkedList
财务数字化转型
Scheme and software analysis of dual computer hot standby system "suggestions collection"
Es search summary
【汇编语言实战】一元二次方程ax2+bx+c=0求解(含源码与过程截屏,可修改参数)
配置系统环境变量的时候误删了Path怎么办?
Vim: use tags file to extend the automatic code completion function of YCM for the third-party library of C language
[don't bother to strengthen learning] video notes (IV) 2. Dqn realizes maze walking
gnuplot软件学习笔记
DSP development, using CCS software to establish engineering and burning
Introduction to common ansible modules
Android系统安全 — 5.3-APK V2签名介绍
Detailed LinkedList
TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
Replace the function of pow with two-dimensional array (solve the time overrun caused by POW)
Little dolphin "transformed" into a new intelligent scheduling engine, which can be explained in simple terms in the practical development and application of DDS
数据中台:始于阿里,兴于DaaS
Cess test online line! The first decentralized storage network to provide multiple application scenarios