Question: What is the sum that has been accumulated from 1 to 100?
Non-recursive statement:CopyCodeThe Code is as follows: 1run: function (){
2 var sum = 0;
3 For (VAR I = 1; I <= 100; I ++ ){
4 sum = sum + I;
5}
6 console. Log (SUM );
7}
Recursive Syntax:
Copy code The Code is as follows: var testcase = {
Sum: 0,
Run: function (n ){
If (n> = 100 ){
Return 100;
}
Else {
Sum = N + testcase. Run (n + 1 );
Return sum;
}
}
};
Console. Log (testcase. Run (1 ));
The above code is a lot of online searches, and the following code is equivalent to it:Copy codeThe Code is as follows: console. Log (function (n ){
VaR sum = 0;
If (n <= 1 ){
Return 1;
}
Else {
Sum = arguments. callee (n-1) + N;
Return sum;
}
}) (100 ));
This method is easy to learn. The above is linear recursion. It's okay to get started with recursion,AlgorithmThe performance efficiency is worse, not to be considered.