js recursive implementation

definition:

This function is a recursive function calls functions in the body;

Recursive function should pay attention to the function terminates conditions to avoid an endless loop;

Recursive form:

1. Declare a named function, invoked by the function name

function f(a){
    if(a<=1){
        return 1
    }else{
        return a*f(a-1)
    }
}     

But this use because of the change of name of the function f and error,

f = null
f ()  // Uncaught TypeError: f is not a function

2. Use arguments.callee instead of the function name

It does not support the use of arguments.callee in strict mode

h3. function expression

 

var fun = (function f(a){
    if(a<=1){
        return 1
    }else{
        return a*f(a-1)
    }
})

// 或:

var f = function (a){
    if(a<=1){
        return 1
    }else{
        return a*f(a-1)
    }
}

var fun = f;

 

Guess you like

Origin www.cnblogs.com/lizhiwei8/p/11526377.html