Ban against the war! js recursion function on the basis of

Recursive function features:

1, the function calls itself

2, the general will return

3, there will be general parameters

note:

**** recursive loop can do everything can do, but also to solve the cycle is not easy to resolve the matter

**** sometimes do not understand recursion is how to properly implement the function (because of the routine)

In general companies which expressly prohibit the use of recursion , but understand recursion is also a Knowledge for programmers! ! ! !

As for why the company does not allow recursion, for the following reasons:

    Case: 1 to 100 is calculated and

Use common loop:

<script>
        function add(a) {
            var sum=0
            for(var i = 1;i <= a;i++){
                sum += i
            }
            return(sum)
        }
        document.write(add(100))
</script>

5050 results

Recursive thought:

Write recursive routines:

  1. Find the critical value, typically an initial value need not be calculated (for the chain breaking recursive, recursive realization)

  2. Find this time is calculated with the previous relationship

  3. Call own calculations Previous

 

It is then calculated according to any of 1 to 100 and

Defined functions add ()

Obviously, the first calculation is counted and 1, the result is 1, it found an initial value of 1

Then we can know, if you want to count the 9th, we need +10 9th, that is,

add(10)=add(9)+10

So the general rule is found: add (n) = add (n-1) + n

So recursive function so you can write:

<script>
        function add(a) {
            var sum = 0
            if( a==1){
                return 1;
            }
            sum = add(a-1) + a
            return sum;
        }
        document.write(add(100))
</script>

Recursive thinking is very interesting, to reduce the amount of code that will make the

But it also has a fatal weakness:

Their memory is a waste of resources, call functions, the program will allocate memory space, the program can be run over release

But the idea will make a recursive function calls itself a lot of, but not on a calculated value, the next value can not be calculated, which is allocated memory is not released before

When we recursively to the limit, the function will complete the work fast, and release the memory, speed of the computer to do this very quickly, it will be too much memory hardware

If we calculate 1 to 10 billion, it is clear that this small program may finish occupy all the memory that the computer crashes, working company uses a recursive function can be very dangerous! ! ! !

Guess you like

Origin www.cnblogs.com/lanbai/p/12640008.html