Home > Web Front-end > JS Tutorial > body text

Recursively call function method

一个新手
Release: 2017-09-21 09:54:50
Original
1726 people have browsed it

Recursive call (---Fibonacci sequence)

Recursive: Call yourself again inside a function;

Efficiency: This call has not yet ended , the next call will start, and this call will be suspended until all calls are completed before returning in sequence.

It is shaped like a mathematical function: the factorial of f(n)

##ex: 5!=5*4! (5* 4*3*2*1)

4!=4*3! (4*3*2*1)

3!=3*2! (3*2*1)

2!=2*1! ( 2*1)

##1!=1;

F(n)! =n*f(n-1)!

<script>
	//计算数字n的阶乘 (if方法)
		function f(n){
			if(n==1){            //边界条件
				return 1;
			}else{               //没到边界条件
				return n*f(n-1);
			}
		}

	/*或者:return n==1 ? 1 : n*f(n-1); (三目运算方法)
		function f(n){
			var result = return n==1 ? 1 : n*f(n-1);
			return result;
		}
	*/
		//计算5的阶乘?
		function testF(){
			var result = f(5);
			console.log(result);
		}
		testF();
	</script>	
Copy after login

Exercise:

The following sequence: Fibonacci sequence
1,1,2,3,5,8,13 ,21,34,55………….
Known: The first number and the second number in the sequence are both 1
From the third Starting with numbers, each number is the sum of the previous two numbers

Question: Use a function to find the nth number in the sequence The value of

##

<!doctype html>
<html lang="en">
 <head>
	 <meta charset="UTF-8">
     <title>Document</title>
	 <link rel="stylesheet" style="text/css" href="">
	 <style>
	 </style>
 </head>
 <body>
	<script>
	 function f(n){
			if(n==1 || n==2){
			  return 1;
			 }else{
			  return f(n-1)+f(n-2);
			 }
		}
		function testF(){
		var result=f(20);
		console.log(result);
		}
		testF();
	</script>	
 </body>
</html>
Copy after login

The above is the detailed content of Recursively call function method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!