Recursive programming in Javascript

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.