Home  >  Article  >  Web Front-end  >  Recursive function in JS

Recursive function in JS

高洛峰
高洛峰Original
2017-02-08 15:24:431574browse

In programming languages, when function Func(Type a,...) directly or indirectly calls the function itself, the function is called a recursive function. Recursive functions cannot be defined as inline functions.

Recursive function:

function factorical(num){
  if(num<=1){
    return 1;
  }
  else{
    return num*factorical(num-1);
  }
}
factorial(2)//2

This recursive function uses a function to call the function itself, but is this really good? Next, look here

var another=factorical;
factorical=null;
console.log(another(2))//会报错说 factorical not a function

This is the disadvantage of function calling function, so how to solve it, look below

function factorical(num){
  if(num<=1){
    return 1;
  }
  else{
    return num*arguments.callee(num-1);
  }
}
var another=factorical;
factorical=null;
console.log(another(2))//2

Using arguments.callee instead of the function name above ensures that no error occurs no matter how the function is called.

The above is the recursive function in JS introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to recursive functions in JS, please pay attention to the PHP Chinese website!

Statement:
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