Good programmers web front-end share function scope and recursion

Scope life cycle.

 

There are a = 10;

 

function m1(){ 

    There are a = 5;

    alert(a);

}

 

Parameter (formal parameter) and arguments (actual parameters) significant difference

 

There are a = 10;

 

var x = 0;

 

function fn(x){

 

    x =a + 10;

 

}

 

fn (a); 

 

Recursive usage

 

What is recursion?

 

Their calls itself!

 

function pr(){

 

    Return Q ()

 

}

 

key point:

 

1. termination condition

 

2. operation rule

 

function pr(n){

      

     if (n == 1) {// termination condition

          return n;

     }

 

     Return  not Q (n-1) +;    

 

}

 

Print any number of hello world;

 

function pr(n){

 

    if(n==0){

        return

    }

 

    document.write('hello world!!<br>');

 

    Return Q (n-1);

 

}

per (10)

Case: find n numbers and, 5 calculates 1 + 2 + 3 + 4 + 5

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title></title>

</head>

<body>

 

</body>

<script type="text/javascript">

// function declaration

function getSum(x) {

if (x == 1) {

return 1;

}

return x + getSum(x - 1);

}

// call the function

console.log(getSum(5));

</script>

</html>

案例:输出斐波那契额数列数列的前20项(递归)

 

斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title></title>

</head>

<body>

 

</body>

<script type="text/javascript">

function fib(n) {

if (n == 1 || n == 2) {

return 1

}

return fib(n - 1) + fib(n - 2)

}

for (var i = 1; i <= 20; i++) {

document.write(fib(i) + '<br>')

}

</script>

</html>


Guess you like

Origin blog.51cto.com/14249543/2404911