- 1
How this code alert 1.
function func(n) { if(n<=1) { return 1; } else { return func(n-1); } } alert(func(4));
3 Réponses
+ 3
1st call:
n = 4;
if = false; else = true
else returns func(4 - 1) // n = 3
2nd call by else:
n = 3;
if false; else = true
else return func(3 - 1) // n = 2
3rd call by else:
n = 2;
if false; else true
else return func(2 - 1) // n = 1
4th call by else:
n = 1;
if true; else = false
if returns 1 // no more func() calls by else, code stops
+ 7
Because you told it to do so
...return 1;
if you say "return 100;"
100 will be the output.
try this...
var n;
function func(n) {
if(n<=1) {
return n;
} else {
return func(n-1);
}
}
alert(func(parseInt(prompt())));
with the above code, every input will give "1"
since it returns the final value of n as @Ben Bright explained
+ 2
thanks brother for clear this misunderstand.