Use JavaScript to implement the factorial of n: 1. Use while loop, code such as "while(num){result *= num;num--;}"; 2. Use function recursion, code such as " if(num <= 0){return 1;}else{...}".
The operating environment of this article: windows7 system, javascript1.8.5 version, Dell G3 computer.
How to use javascript to implement the factorial of n?
Two methods to implement n factorial in javascript
Option 1: Using while loop
function factorial(num){ var result = 1; while(num){ result *= num; num--; } return result; }
Option 2: Using function recursion
function factorial(num){ if(num <= 0){ return 1; }else{ return num*arguments.callee(num-1); } }
Recommended Study: "javascript basic tutorial"
The above is the detailed content of How to implement the factorial of n using javascript. For more information, please follow other related articles on the PHP Chinese website!