Home  >  Article  >  Web Front-end  >  Recursive programming in JavaScript language_javascript skills

Recursive programming in JavaScript language_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:26:50832browse

Question: What is the sum of adding up from 1 to 100?

Non-recursive loop writing:

Copy code The 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 writing:

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));

There are a lot of codes like the above found on the Internet. The following writing method is equivalent to it:
Copy code The 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 way of writing is easy to learn. The above is linear recursion, which is fine as an introduction to recursion. However, the performance efficiency of the algorithm is a bit poor and will not be considered.
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